Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Slow in-memory-backend for email in my Django 2.2 tests
I am using an in-memory-backend for email in my Django 2.2 tests. The documentation mentions: The outbox attribute is created when the first message is sent. It’s a list with an EmailMessage instance for each message that would be sent. This works fine and dandy, but it takes five seconds to initialize this outbox attribute. This basically increases my total test time of the test suite from 1 second to 6 seconds. When sending a second email in another test case in the same run, this occurs instantly, so it must be related to the setting up, but I don't know how to speed this up. Any thoughts? -
In django model what are the pros and cons of setting null=True or blank=True?
In a django model, I usually take the lazy/easy way our to set all my CharFields to both null=True and blank=True. I am going to remove one, but which one is more preferable to keep? I am using MySQL by the way. -
How to use model methods in django templates with class based view
I've defined methods in my model, and I'm trying to use it in django template, which is rendered using ListView My model looks like this: class Book(models.Model): name = models.CharField(max_length=32) price = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def get_total_sum(self): return super().objects.all().filter(user=self.user).aggregate(models.Sum('price')) My view: from django.views.generic.list import ListView from book.models import Book class BookView(ListView): template_name = 'book.html' # I'm using this to order book by created date def get_queryset(self): return Book.objects.filter(user=self.request.user).order_by('-created_at') And my template: Total books: {{ object_list|length }} Total price of all books: # I've no idea how to display them here, when using class based view -
How to check the diff in two models in django
Suppose I program a "Job" to process the input and give an output. It produces many different objects and be stored in different database tables (12~20 models) I need to diff two jobs output, users may have some modified in the input and leads to the output change. I need to find out which instances are changed in the models. I tried to add the compare() method to each model and use the name to index the instance in two Jobs. (Found=>Compare) class ModelA(models.Model): job_id = models.IntegerField() name = models.CharField(max_length=31) content1 = models.CharField(max_length=128) content2 = models.CharField(max_length=128) content2 = models.CharField(max_length=128) def compare(self, comp) excluded = "id", "job_id" d1, d2 = self.__dict__, comp.__dict__ for k, v in d1.items(): if k in excluded: continue if v != d2[k]: return False return True Most of the models which have a mutual name index may work, I can use the name to find the mutual instance in two jobs and then call the compare() to test the difference. However, in some models, the name is not a very proper way to index two instances since the name is more like an order. So the instance name may shift if new instances are added in the … -
Django: Heroku Failing to launch, at=error code=H10 desc=“App crashed”
Trying to launch my web app for the past 3 days and I keep getting this error. before the app is working perfectly without any error. I view my logs but cannot seem to decipher where the error is coming from or how to begin to debug. I don't even know what to do now because I am really tired. If anyone can help that would be amazing! Thank you! 2019-10-31T15:19:04.996635+00:00 app[web.1]: [2019-10-31 15:19:04 +0000] [11] [INFO] Worker exiting (pid: 11) 2019-10-31T15:19:04.998991+00:00 app[web.1]: [2019-10-31 15:19:04 +0000] [4] [INFO] Handling signal: term 2019-10-31T15:19:05.203657+00:00 app[web.1]: [2019-10-31 15:19:05 +0000] [4] [INFO] Shutting down: Master 2019-10-31T15:19:11.689709+00:00 heroku[web.1]: State changed from starting to up 2019-10-31T15:19:11.608486+00:00 app[web.1]: [2019-10-31 15:19:11 +0000] [4] [INFO] Starting gunicorn 19.9.0 2019-10-31T15:19:11.609129+00:00 app[web.1]: [2019-10-31 15:19:11 +0000] [4] [INFO] Listening at: http://0.0.0.0:49822 ( 4) 2019-10-31T15:19:11.60926+00:00 app[web.1]: [2019-10-31 15:19:11 +0000] [4] [INFO] Using worker: sync 2019-10-31T15:19:11.61345+00:00 app[web.1]: [2019-10-31 15:19:11 +0000] [10] [INFO] Booting worker with pid: 10 2019-10-31T15:19:11.652534+00:00 app[web.1]: [2019-10-31 15:19:11 +0000] [11] [INFO] Booting worker with pid: 11 2019-10-31T15:19:32.839267+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=selmee.he rokuapp.com request_id=c3a5ba3c-b692-4541-a43b-8fdead5e5adc fwd="197.210.84.35" dyno= connect= service= status=503 bytes = protocol=https 2019-10-31T15:29:47+00:00 app[api]: Build started by user musty474izala@gmail.com 2019-10-31T15:30:14.108522+00:00 heroku[web.1]: State changed from up to down 2019-10-31T15:30:12.243748+00:00 … -
Data from django to JS
I have some data on my django views, and I will pass it to my django templates with some variable. Let's supose that I'm giving to my views a list called 'listone', and on the view I created a list on JS, now I want to pass the listone data to the js list, Is this even possible or there are other way to do it? -
Do i need models.py even for ready made mysql databases?
I spin up a django project. Afterwards, i didn't write models.py but instead I created a database from MySQL command line(independent from django) and created three tables with required columns. Finally i connected my django app with that database successfully. I applied migrations. But now i am confused do i need to write models.py with every field name as in column? I remember implementing a basic project in which i did write models.py and created database using "python manage.py shell" and then put values using "from polls.models import Choice, Question"? How do i put data now initially and then using python on some action from UI? -
Ajax Triggered request doesn't update Django View
I tried to break this problem down into the simplest example. When the request is ajax, rendering the page with an updated context doesn't produce the expected result. index.html: <html> <body> {% if templateVariable %} <h1>{{ templateVariable }}</h1> {% endif %} <button id="testBtn">TEST</button> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { $(function() { $('#testBtn').click(function(event) { $.ajax({ type: "POST", url: "./", data: { 'x' : 'x', 'csrfmiddlewaretoken' : '{{ csrf_token }}' } }); }); }); }); </script> </body> </html> views.py def index(request): context = {} if 'x' in request.POST: context['templateVariable'] = 'I was updated via ajax' print('ajax ran') return render(request, 'index.html', context) context['templateVariable'] = 'I was not updated via ajax' print('ajax was not run') return render(request, 'index.html', context) When I first load the page, 'ajax was not run' is printed, templateVariable is 'I was not updated via ajax', and the page renders with that in the h1 tag as expected. When I click the testBtn, I expect the ajax request to trigger the if statement, update the context, and render the page with 'I was updated by ajax' in the h1 tag. Instead, 'ajax ran' is printed but templateVariable remains 'I was not updated by ajax' when the page … -
supervisorctl - projworker: ERROR (no such file)
Path to root of project: /home/user/projects/proj /etc/supervisor/conf.d/celery_proj_worker.conf [program:projworker] command=/home/user/.virtualenvs/proj/bin/celery -A proj worker -l info directory=/home/user/projects/proj user=user numprocs=1 autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=998 -
Is there a way to add models to postgres without deleting all the tables in postgres?
Django I am trying to add a new table/model from Django models to my existing postgres database with tables already but the only solution is to start from scratch again Solution: Delete migrations, delete all the tables in the postgres database. python manage.py makemigrations, python manage.py migrate Error: The table does not exist when browsing the drf api or the postgres database after trying to makemigrations and migrate with the new models. -
Django prefetch_related on ManyToMany(through)
I am attempting to minimize my number of queries on a ManyToMany(through=), but I seem to be causing an n+1 simply by prefetching. Models: class Member(ImmutableModel): organizations = models.ManyToManyField('Organizations', through='MemberOrg', related_name='members') class MemberOrg(ImmutableModel): member = models.ForeignKey('Member', related_name='member_orgs') org = models.ForeignKey('Organization', related_name='member_orgs') class Organization(ImmutableModel): From a clean database, if I setup these models: member = Member.objects.create() org = Organization.objects.create() MemberOrg.objects.create(member=member, org=org) MemberOrg.objects.create(member=member, org=org) Then fetch: Member.objects.all().prefetch_related('member_orgs') I get the following queries: (0.009) SELECT "main_member"."id", (...) FROM "main_member"; args=() (0.010) SELECT "main_memberorg"."id", (...) FROM "main_memberorg" WHERE "main_memberorg"."member_id" IN (1); args=(1,) (0.005) SELECT "main_member"."id", (...) FROM "main_member" WHERE "main_member"."id" = 1; args=(1,) (0.003) SELECT "main_member"."id", (...) FROM "main_member" WHERE "main_member"."id" = 1; args=(1,) I am trying to figure out why I am getting one query of the Member model per MemberOrg. This behavior continues as I add MemberOrg-s. I can't find any mention of this in the docs, and these questions suggest this is how they solved the problem, but it doesn't seem to be working as intended for me. (Note: This is just an example schema - my requirements are more complex and I am tied to this model setup.) Django: 1.9.1 postgres: 9.6 -
In django, how do you create many to many relationshipd between models
Say i have 3 models (Actor, Movie and Series) defined like this: class Actor(models.Model): name = charField... date_of_birth = ... filmography = (list of Series and Movie objects) class Movie(models.Model): name = ... genre = ... cast = (list of Actor objects) class Series(models.Model): name = ... no_of_eps = ... cast = (list of Actor objects) How do i make a many to many relationship between 'actor and movie' and 'actor and series' where actor can store a number of movies and tv shows in its filmography field and movie and series can store a number of actors in there respective cast fields. (Ignore lack of inheritance for movie and series unless it's the only solution) -
ModelForm not creating a new entry in Database
I am trying to get my form to save the responses to the database however a new entry isn't being created in the database when I try to check via the admin section. When I hit the next button the page reloads like it's supposed to and no errors pop up. I deleted the db.sqlite3 file and re-ran the migrations but it still didn't seem to work. The other forms are saving the data to the database. The issue is only with this form. Can you tell me what changes I should make? Thanks in advance views.py def qone(request): if request.method == "GET": global starttime starttime = my_timer() form.save() elif request.method == "POST": form = Question1Form(request.POST) if form.is_valid(): global endtime endtime = my_timer() global timespent1 timespent1 = "{0} seconds".format(endtime - starttime) form.save(commit=True) else: form = Question1Form() form = Question1Form() return render(request,'question1.html',{'form':form}) models.py class Responses(models.Model): question1 = models.TextField() question2 = models.TextField() question3 = models.TextField() timespent1 = models.TimeField(null=False) forms.py class Question1Form(forms.ModelForm): question1 = forms.CharField() timespent1 = forms.TimeField(widget=forms.HiddenInput()) class Meta: model = Responses fields = ('question1','timespent1') html {% extends 'base.html' %} {% block content %} {% load staticfiles %} <div class="container"> <form method="POST"> {% csrf_token %} {{form.as_p}} <input type="Submit" name="" value="Next"> </form> </div> … -
The current path, FOUR/index/{ % url 'four:test' 1 %}, didn't match any of these
My template does not pass parameters and will not report an error, but the parameters will be reported incorrectly, please help me. my urls.py is: from django.urls import re_path from FOUR import views app_name = "four" urlpatterns = [ re_path(r'mmmm', views.mmmm, name='mmmm'), re_path(r'gettime/(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/$', views.gettime, name='gettime'), ] my views.py is : def mmmm(request): return render(request, 'test3.html') def gettime(request, year, day, month): return HttpResponse("time is %s-%s-%s" % (year, month, day)) my html is: <a href="{ % url 'aaa:mmmm' % }">mmmmm</a><br> <a href="{ % url 'gettime' year=2019 month=12 day=18 %}">cmdb/userinfo/tom/tomnickname/10</a><br> mmmmm is OK,cmdb/userinfo/tom/tomnickname/10 The following error will occur enter image description here -
How to fix a lot of duplicates of sql queries in Django admin?
I have a custom user who has only one field added. I installed the django debugger and saw that when creating a user and most likely when changing, a lot of identical requests are created. How to fix it? models.py class CustomUserManager(UserManager): pass class TestUser(AbstractUser): phone = PhoneNumberField(null=False, blank=False, unique=True) email = CharField(unique=True, max_length=35, null=False, blank=False) class Meta: db_table = '"fyzzys"."users"' permissions = [ ("can_see_payments", "payments"), ("can_see_analytics", "analytics"), ("can_see_documents", "documents"), ("can_see_sverka", "sverka"), ("can_see_ways", "ways") ] objects = CustomUserManager() def __str__(self): return self.username admin.py admin.site.register(Permission) class MyUserAdmin(UserAdmin): model = TestUser form = CustomUserChangeForm add_form = CustomUserCreationForm list_display = ('username', 'first_name', 'email', 'phone', 'is_active',) list_filter = (['is_active']) search_fields = () filter_horizontal = (['groups', 'user_permissions']) fieldsets = ( ('Personal info', {'fields': ('first_name', 'email', 'phone', 'password')}), ('permissions', {'fields': ('is_active', 'is_staff', 'user_permissions')}) ) add_fieldsets = UserAdmin.add_fieldsets + ( ('Personal info', {'fields': ('first_name', 'email', 'phone')}), ('permissions', {'fields': ('is_active', 'is_staff', 'user_permissions')}), ) admin.site.register(TestUser, MyUserAdmin) -
Every time that I try to use connection.cursor I get an error
I'm trying to add an script to my project to check the connection to the DB, but every time that I try to use 'connection.cursor()' or 'connection.ensure_connection()' gives me an error. Any idea what could it be. from django.db import connection def snapshot(): try: connection.ensure_connection() except: print('not connected') else: print('connected') snapshot() Traceback (most recent call last): File "Fufillment_Portal/savedb.py", line 82, in <module> snapshot() File "Fufillment_Portal/savedb.py", line 31, in snapshot cursor = connection.cursor() File "/usr/local/lib/python3.7/site-packages/django/db/__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 198, in __getitem__ self.ensure_defaults(alias) File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 166, in ensure_defaults conn = self.databases[alias] File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 147, in databases self._databases = settings.DATABASES File "/usr/local/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/usr/local/lib/python3.7/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.7/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in … -
Django formset is_valid fails Cannot assign "u'username'": "contact" must be a "User" instance
I have a django inline formset that populates a bunch of forms. One of the field is a contact entry which would a be user name. User can select the user name and data is sent in Post call. Problem is the formset.is_valid call fails because of the error. I specifically converted the contact value in request object to specified user object but Django somehow later again converts it a unicode string and i get the error. Not sure whats happening here. Model: class ATest(models.Model): contact = models.ForeignKey('auth.User', related_name='test_contact', null=True, blank=True) View (Post Call): request.POST['atest-0-contact'] = GetOrCreateUserMixin.get_or_create_user(request.POST['atest-0-contact']) ctx['formset_test'] \ = formset_test \ = TestAFormSet( request.POST, instance = test ) is_valid = formset_test.is_valid() Form: class ATestForm(forms.ModelForm, GetOrCreateUserMixin): contact = forms.CharField( label='Contact', widget=forms.TextInput(attrs={ 'autocomplete': 'off', 'class': 'js-widget-user-typeahead', 'style': 'width: 95%' }), # help_text='Begin typing user name', required=False ) class Meta: model = models.ATest fields = ( 'contact', ) def __init__(self, *args, **kwargs): self.conflict = {} self.user = kwargs.pop('user') super(ATestForm, self).__init__(*args, **kwargs) self.original = {} self.fk_display_fields = ( # contact, ) if contact in self.fields: self.fields[contact].help_text = '' self.fields[contact].label = '' def clean_contact(self): if not self.cleaned_data[contact]: return None return self.get_or_create_user(self.cleaned_data[contact]) TestAFormSet = inlineformset_factory(models.Test, models.ATest, form=ATestForm, formset=BaseAutomationFormSet, extra=0, help_texts=None, labels=None, can_delete=True) -
Docker & Python, Speed up when your requirements.pip list is huge?
Say you have a rather large requirements.pip when you modify a requirements.pip, it takes ages to build Docker image because it has to download and install all packages in requirements.pip Is there a way to speed up the docker image building process when you modify a length requirements.pip ? -
How to prevent save() from update created timestamp
My django app has a table with a datetime field date_created, which is set default to CURRENT_TIMESTAMP. The database is MySQL. When I update a record to change a certain field (say, rank). I did the following: >>> from orchiddb.models import HybImages >>> >>> id = 39387 >>> image = HybImages.objects.get(pk=id) >>> image.date_created datetime.datetime(2019, 5, 24, 15, 28, 29, tzinfo=<UTC>) >>> image.rank = 1 >>> image.save() >>> image.date_created datetime.datetime(2019, 10, 31, 14, 14, 51, 852406, tzinfo=<UTC>) Why did the date_created value changed (and what 852406 stand for)? What do I have to do to keep date_created unchanged? -
Problem when creating a form with both django-autocomplet-light and and bootstrap-datepicker-plus widgets
I am trying to create a form which uses two different widgets: - some fields are using django-automplete-light ModelSelect2 widget - another field is using bootstrap_datepicker_plus DatePickerInput widget However, I can't manage to make them both work: when I create a form with DatePickerInput only, the calendar shows correctly, but when I add fields using ModelSelect2, the calendar doesn't popup anymore. Does anybody know what could cause this problem and how to solve it? In settings.py I set 'include_jquery' = True for BOOTSTRAP4 Below is an extract of the form code: from django.forms import ModelForm from dal import autocomplete from bootstrap_datepicker_plus import DatePickerInput class CreateWhoForm(ModelForm): class Meta: model = m.Who fields = ( 'why', 'how', 'begins' ) widgets = { # when 'why' and 'how' are commented, DatePickerInput() calendar widget shows correctly # when they are present, the calendar widget doesn't show anymore 'why': autocomplete.ModelSelect2( url='core:why-autocomplete' ), 'how': autocomplete.ModelSelect2( url='core:how-autocomplete' ), 'begins': DatePickerInput() } And some of the html used: <pre> {% load static %} {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {{ form.media }} {% for field in form %} <div class="form-group{% if field.errors %} has-error{% endif %}"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {% … -
Add sitemap on external server to Django Sitemap
Django has a built-in Sitemap class to generate a sitemap.xml from the urls it contains (well - the user has pointed to). That's great. But my blog to my web app (which is on e.g. mysite.com) is hosted on a different server and run using WordPress. The blog URL is blog.mysite.com. My question is: is there a way to use the django built-in sitemap class to add this external url (blog.mysite.com) to the generated sitemap.xml? If not - what is the best way to create the sitemap file? Wordpress also generates a sitemap on its own, so I need a reference in the django generated sitemap.xml pointing to the WP sitemap.xml. But how to link those two? -
Correct Displaying Django Forms
I`ve stacked w problem that i wrote similar code for 2 html pages on my website First page is situated on 127.0.0.1 and second is on 127.0.0.1/accounts/signup Browser parsing it and getting the same code from the 2 files gives 2 different answers 127.0.0.1 has no such code in generated html file <p><label for="id_email">Email:</label> <input type="email" name="email" placeholder="EmailAddress"id="id_email"></p> <p><label for="id_password1">Password:</label> <input type="password" name="password1" placeholder="Password" required id="id_password1"></p> But 127.0.0.1/accounts/signup has How to fix it, i need my forms on 127.0.0.1 What i`ve 2 do ? -
why am I getting previous django project's css instead of current django project?
I made static directory inside my app and kept my css folder inside static with the name style.css. I set the css link as : <link rel="stylesheet" href="{% static 'css/style.css' %}"> I think all the path is correct but it shows the previous project's css. why this is happening? -
Django Invalid column name with SQL Server, but query works in the shell
I'm trying to make this work in django. I'm using django_filters and django ORM for the query. The query doesn't show any errors when i run it in the shell, but when i do python manage.py runserver, I get this error in the browser: ('42S22', "[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'ARecordID'. (207) (SQLExecDirectW); [42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") When I use ARecordID in a raw sql query it works, but I don't want to work with raw queries since I want to be able to use django_filters. This is what I have(changed field names and model names to make things easier(relatively)): models.py: class modelA(models.Model): arecordid = models.IntegerField(db_column='ARecordID', primary_key=True) # Field name made lowercase. name = models.CharField(..) .. class modelB(models.Model): a = models.ForeignKey('modelA', db_column='ARecordID', on_delete=models.CASCADE, db_constraint=False) number = modelsIntegerField(..) .. views.py: a_list = modelB.objects.select_related('a').filter(number=5).values('a__arecordid', 'a__name', 'number', 'phone') filter = aFilter(request.GET, queryset = a_list) return render(request, "template.html", {'filter': filter}) template.html: {% block content %} <form method="get"> {{ filter.form.as_p }} <button type="submit">Search</button> </form> <table> {% for obj in filter.qs %} <tr> <td>{{ obj.number }}</td> <td>{{ obj.a.name }}</td> </tr> {% endfor %} </table> {% endblock %} Any help is appreciated! -
How can I go back a migration on Django?
I put accidentaly a default value 'string' to an integerfield on the migration, now I've been having problems with that, how can I go back to the previuosly migration or delete this field? ValueError: invalid literal for int() with base 10: 'modulo'