Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where do custom model fields get converted to their db_type?
I'm a bit confused here. I wrote a custom model field called PriceField that returns an instance of my class Price from its from_db_value and to_python methods, which both convert from strings to instances of Price. My db_type method returns "string" because I want values of the field to be represented as strings in the database. When I go to add a model that contains a PriceField to the database, I'm getting InterfaceError: binding parameter 3. The params value for the sql statement is [1, 'test', 'desc', <utils.Price object at 0x7f159d9e6da0>, '2019-02-22 00:39:31.634898', 'FS', True, True, True, True, True, '', ''] I'm pretty sure that <utils.Price object at 0x7f159d9e6da0> is my problem- how do I get that converted to a string so the database can accept it? I already have __str__ methods for my Price and PriceField classes. -
Create model instance twice from one form
I have a page that displays a lesson, which includes a DateTime. The lesson model also has an attribute called lesson_weekly, that is a checkbox that a user selects if they want to repeat the object every week. For example, if the date is set as 2019-01-01 10:00 am, and lesson_weekly is checked, I want the lesson object to be duplicated and displayed, but with +7 to the date, so the date would be 2019-01-08 10:00 am. I believe this can be done by simply adding 7 days to this date, but am unsure how to do it so that it works properly and the date switches to the next month if it passes the last date such as the 30th or 31st. I would appreciate any suggestions in how to do this. models.py class Lesson(models.Model): user = models.ForeignKey(User, null=True, default=None, related_name='lessons', on_delete=models.CASCADE) lesson_instrument = models.CharField(max_length=255, choices=instrument_list, blank=True) lesson_level = models.CharField(max_length=255, choices=level_list, blank=True) lesson_length = models.CharField(max_length=255, choices=length_list, blank=True) lesson_datetime_start = models.DateTimeField(null=True, blank=True) lesson_weekly = models.BooleanField(default=False, blank=True) def __str__(self): return self.lessons @receiver(post_save, sender=User) def create_user_lessons(sender, instance, created, **kwargs): if created: Lesson.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_lessons(sender, instance, **kwargs): for lesson in instance.lessons.all(): lesson.save() forms.py class LessonForm(forms.ModelForm): lesson_instrument = forms.ChoiceField(choices=instrument_list, widget=forms.Select(attrs={'class' : 'form-control', … -
Why do my websockets not connect right away when django channels dev server starts up?
I have a django channels project. I'm currently using the ASGI/Channels version 2.1.7 development server When I start up the server, and connect to it with a browser, the HTTP requests start getting served right away, and the HTML page loads in the browser. As soon as the page loads, it tries to establish a websocket connection, which fails. I'm using reconnecting-websocket library, so it keeps trying, and failing. I can see it failing because there are messages in the firefox console that say the connection attempt failed. Refreshing the page doesn't help. After about 30-45 seconds, it starts working. At that point, as long as I keep the development server running, I have zero issues with my websockets - they always connect right away when I load a page that uses them. The problem doesn't always appear (sometimes it works right away), but when it doesn't, it's always the first 30-45 seconds after starting the development server. It's very annoying to have to wait 30-45 seconds during development every time I need to restart the dev server. A tcpdump on the server shows websocket requests coming in with a proper destination port, but getting a TCP RST. The failed … -
Apply the django-vote application in the comment system
I am use django-vote system for my project but i got a some issue. Django-vote system working only get() method. (look at: https://github.com/shanbay/django-vote). I want to add vote to comments but one article has got a multiple comments therefore django-vote not working and give error. MultipleObjectsReturned: get() returned more than one items -- it returned 3!. How can i fix it? -
Add additional fields after phone number lookup in the database in Django
I am building an app that look for each phone number in the database. If there is any duplicate, I want to grab the first phone number found as the main record for that phone number, then for the duplicate information(name, location), get each one of those fields, and add it to the main record phone number fields (name, location), separated by a semi colon. The outcome would look like this after checking the duplicate information of the main phone number record found: Name Location Phone number Helene,Sandra New Yok, Boston 000-000 Please find my model below: class Document(models.Model): name = models.CharField(null=True, max_length=254, blank=True) location = models.CharField(null=True, max_length=254, blank=True) phone_number = models.CharField(null=True, max_length=254, blank=True) I am a bit lost on to achieve the above. Any help would be much appreciated. -
How to import a Wagtail page on all the other wagtail pages
I want to add some content on one of my Wagtail pages and I am trying to import that Wagtail page on all my other wagtail pages. The reason I am trying to do this is that if in the future I make a change on the content it should consistently reflect on all the other Wagtail pages. Is there a way that I can import a Wagtail page on all my other Wagtail pages, if so please let me know. Thanks in advance! I have a website which has the following Configurations: 1) Django-2.0.8 2) Wagtail-2.2.4 -
How to create indexes using a CharField in Django?
I have this following model definition: class Shop(models.Model): label = models.CharField(max_length=50, unique=True, primary_key=True) class Product(models.Model): shop = models.ForeignKey(Shop, on_delete=models.CASCADE, db_index=True) name = models.CharField(max_length=255) price = models.DecimalField(max_digits=12, decimal_places=2) Because Shop has a CharField as a primary key, I want to index my Product table based on that CharField, referenced using a foreign key. With the above setup, how do I write queries which will make sure the index is being used, so products can be retrieved faster? Lets say I write a query as follows: Product.objects.filter(shop="Amazon", price__gte="10.00") Will this query automatically use the indexing set on my models, and therefore make the query faster for large data sets? Or do I have to something extra? -
Repeat date object weekly
I have a page that displays a lesson, which includes a DateTime. The lesson model also has an attribute called lesson_weekly, that is a checkbox that a user selects if they want to repeat the object every week. For example, if the date is set as 2019-01-01 10:00 am, and lesson_weekly is checked, I want the lesson object to be duplicated and displayed, but with +7 to the date, so the date would be 2019-01-08 10:00 am. I believe this can be done by simply adding 7 to this date, but am unsure how to do it so that it works properly and the date switches to the next month if it passes the last date such as the 30th or 31st. I would appreciate any suggestions in how to do this. models.py class Lesson(models.Model): user = models.ForeignKey(User, null=True, default=None, related_name='lessons', on_delete=models.CASCADE) lesson_instrument = models.CharField(max_length=255, choices=instrument_list, blank=True) lesson_level = models.CharField(max_length=255, choices=level_list, blank=True) lesson_length = models.CharField(max_length=255, choices=length_list, blank=True) lesson_datetime_start = models.DateTimeField(null=True, blank=True) lesson_weekly = models.BooleanField(default=False, blank=True) def __str__(self): return self.lessons @receiver(post_save, sender=User) def create_user_lessons(sender, instance, created, **kwargs): if created: Lesson.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_lessons(sender, instance, **kwargs): for lesson in instance.lessons.all(): lesson.save() forms.py class LessonForm(forms.ModelForm): lesson_instrument = forms.ChoiceField(choices=instrument_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' … -
Is it possible to combine multiple values_list() in Django?
As the title suggests, I have multiple sets of queries that each return a values list. I then use the values list to filter another queryset. At the moment I can only do this second step one queryset at a time. Is it possible to combine my initial values lists into one super long list? I'm trying to create an activity/news feed like feature. views.py: cookie_ids = Cookie.objects.filter(board__pk=self.kwargs['pk']).values_list('id', flat=True) sugar_ids = Sugar.objects.filter(board__pk=self.kwargs['pk']).values_list('id', flat=True) **then: context['cookie_actions'] = Action.objects.filter(target_id__in=cookie_ids) context['sugar_actions'] = Action.objects.filter(target_id__in=sugar_ids) -
When to hit API vs Django Built-in Functions
I have a website/native app combo built using django. To support the native app, I built an api backend using django-rest-framework. I read in multiple sources that this was a good idea Now, if I want to interact with my database, I seem to have too many options and I'm wondering what's industry best practice. For example, if I want to surface a simple form to update a User, based on my past django experience, I would lean toward creating an UpdateView. However, I'm now wondering if I should instead build a form that posts to my User API endpoint via AJAX. From what I've read, it appears the second option would be more aligned with an API-first approach. However, this would also require that I do more upfront work in effectively rebuilding a lot of built-in django functionality. Also, it seems to me that this is less efficient, as pages that before involved a single HTTP request now will require multiple. Is there any validity to optimization concerns around multiple HTTP requests per page? Is there an upper bound I should be wary of (say for example if I'm allowing a user to update/insert dozens of records on a … -
How to display multiple related foreign keys in a row with the parent
I try to make a table in a template that shows the parent (habit) in the first row and seven children (days) (the foreign-keys) in the next. With a for-loop I tried to repeat the process, but I failed. The desired result should look something like that, but stop after day 7: I need to have a for-loop because I don't know yet how many Habits I have to display. Here my models (abbreviated for clarity): class Habit(models.Model): habit_name = models.CharField(max_length=30) class HabitTracking(models.Model): habit = models.ForeignKey(Habit, on_delete=models.CASCADE, related_name="habit_day") habit_date = models.DateField() My view: from .models import Habit, HabitTracking def habit_list(request): today = datetime.now().date() start_of_week = today - timedelta(days=today.weekday()) end_of_week = start_of_week + timedelta(days=6) habits = Habit.objects.all().order_by('pk') next_7_days = HabitTracking.objects.order_by('habit__id', 'habit_date').filter( habit_date__gte=start_of_week ).filter( habit_date__lte=end_of_week) first_day = HabitTracking.objects.order_by('habit__id').filter( habit_date__gte=start_of_week ).filter( habit_date__lte=start_of_week + timedelta(days=6)) return render(request, 'habit_tracker/habit_list.html', { 'habits': `habits, 'next_7_days': next_7_days, 'today': today.strftime("%d.%m.%y"), 'start_of_week': start_of_week, 'end_of_week': end_of_week, 'first_day': first_day })` And here my template: <table> <thead> <tr> <th>Habit</th> <th>S</th> <th>...</th> </tr> </thead> <tbody> {% for habit in habits %} <tr> <td>{{ habit.habit_name }}</td> {% for day in first_day %} <td>{{ day.habit_date|date:"d" }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> Thank you for guiding me in the right direction. -
Django no migrations to apply, postgresql backup versus droping database dilema
I recently pushed a django app to a live server but then on my local machine I made some changes to the database and then deleted all migration files and recreated them. Thus, when I try to migrate on the live project I get the message No migrations to apply. The live project database already has quite a bit of data in it but it just refuses to pick the changes. The best way to fix this I think would be to back up all my data which I haven't been able to figure out, delete the entire database and repopulate it or a combination of both. I've tried deleting the django_migrations relation. That didn't help. Trying to delete django_content_type relation resulted in an error that it can't be deleted because other relations depend on it. I'd like to back up all the data in my current database, drop the existing database and recreate it so I can migrate with the updates then restore all the data. How would I do that? If there is an even better method of handling this, that would be great too. I should note that the changes I've made to the database are minor … -
Is it needed to install a virtual machine on Windows to develop a Django app that will run on Ubuntu server?
I am just beginning with Django. for the moment I installed PyCharm, Git and MySQL on Windows 10. However the production server will run Ubuntu. Does I need to install a virtual machine and run PyCharm in a virtualized Ubuntu ? -
using pipenv with git submodules
I have a git submodule B, that works as an app in my django project A. B has its own Pipfile and Pifile.lock. A also has a Pipfile and Pipfile.lock. How can I use pipenv, to install the libraries from both pipfiles within the same virtuaelenv? -
(Docker) Django model “doesn't declare an explicit app_label” and isn't in an application in INSTALLED_APPS
I'm trying to dockerize a django server, but I'm facing issues that are poorly documented. I have a very simple Specs model defined in my models.py file, and when I try to run docker-compose I am receiving the following error message: RuntimeError: Model class api.models.Specs doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I then realised that, upon following the tutorial I was using, I did not add my AppConfig name into INSTALLED_APPS, but just that was not enough to resolve the issue. I'm using a different project structure to run this docker container, and I suspect the problem might be related to the path to my apps.py file. Here's a summarized version of the current project file structure: project/ -app/ --app/api/ ---app/api/apps.py ---app/api/controllers.py ---app/api/models.py ---app/api/views.py ---app/api/wsgi.py --app/config/ ---app/config/celeryconfig.py ---app/config/settings.py --app/someUtils/ --app/manage.py -docker-compose.yml -Dockerfile -requirements.txt I have tried using several different values for INSTALLED_APPS, like "apps.MyAppConfig", "api.apps.MyAppConfig" and "app.api.apps.MyAppConfig", but all I get are different error messages, such as "ModuleNotFoundError: No module named <>". Can anyone help me figure out how to fix this? What path should I use for this appConfig in the settings.py's INSTALLED_APPS? Should I change my dockerization approach to something different (free … -
Django custom backend causes error on signin
Wrote custom django backend, after clicking signin button it calls authenticate and fails with error: 'dict' object has no attribute 'backend' I pushed string to authentication backend AUTHENTICATION_BACKENDS = [ 'app_auth.auth_backend.AuthBackend' ] What may go wrong? -
Aws Lambda + Django + django-storages + collectstatic inconsistent behaviour
I am running aws lambda. It is deployed with zappa. Lambda runs a django project. Django uses django-storages lib to use S3 for storage and serving static files. I run collectstatic successfully. I see my admin page with fully loaded js and css. Next day I come back and see plain html admin page without js and css loaded. I continue navigating through admin page and after some time css and js magically loads. Anyone experiencing something similar? Any ideas of why is this happening? -
How to extract Data from Django Queryset
How to retrieve the data from Django queryset for use in a variable When an output is received in below form after running the query <QuerySet [{'name': 'John'}]> I want to use the value 'John' in a variable for further processing. How do I extract this ? -
Django 2.1.5 Authentication (login/logout) breaks on Browser Back-button
I create a simple login logout app using the Out of the box django LoginView and LogoutView. In my app, I can signup using CreateView, list the users using ListView and get user details using DetailView. I am seeing issues with login and logout when I click the browser's back button. Issues: Upon login, I am redirected to index page. However when I click the back button, I land back at login page and can login with other valid user. Upon logout, I am redirected to index page. However when I click the back button, I can view the logged-in data such as the list page and details page. The code for my app (accounts) is : settings.py <code> LOGIN_REDIRECT_URL = "/accounts/" LOGOUT_REDIRECT_URL = "/accounts/" project urls.py <code> urlpatterns = [ path("admin/", admin.site.urls), path("accounts/", include("django.contrib.auth.urls")), path("accounts/", include("accounts.urls")), ] app urls.py <code> from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'accounts_app' urlpatterns = [ path("", views.IndexPage_cview.as_view(), name="index_curl"), path("login/", auth_views.LoginView.as_view(),name='login'), path("logout/", auth_views.LogoutView.as_view(), name="logout"), path("signup/", views.SignUp_cview.as_view(), name="signup_curl"), path("super/", views.adminlist_cview.as_view(), name="super_curl"), path("superdetail/<int:pk>", views.admindetail_cview.as_view(), name="super_detail_curl"), ] app views.py <code> from django.contrib.auth import login, logout from django.urls import reverse_lazy from django.views.generic import TemplateView,CreateView, ListView, DetailView from django.contrib import … -
how to group by a column and pick one object ordered by created time
I have a model like below, class MusicData(BaseModel): name = models.CharField(max_length=100) url = models.URLField() description = models.TextField() age = models.CharField(max_length=25) language = models.ForeignKey(Language, on_delete=models.CASCADE, related_name="music_data", related_query_name="music_data") count = models.IntegerField() last_updated = models.CharField(max_length=255) playlist = models.ForeignKey(PlayList, on_delete=models.CASCADE, related_name="music_data", related_query_name="music_data") I want to get MusicData such that group by name, in each group get the one which has latest created_on (created_on is a DateTimeField in BaseModel) suppose say I have following data | Name | Created On | | ----------- | ----------- | | ABC | 2019-02-22 1:06:45 AM | | ABC | 2019-02-22 1:07:45 AM | | BAC | 2019-02-22 1:08:45 AM | | BAC | 2019-02-22 1:09:45 AM | | BAC | 2019-02-22 1:10:45 AM | | BBC | 2019-02-22 1:11:45 AM | The expected output is that | Name | Created On | | ----------- | ----------- | | ABC | 2019-02-22 1:07:45 AM | | BAC | 2019-02-22 1:10:45 AM | | BBC | 2019-02-22 1:11:45 AM | I have written this query, which is working fine for above case models.MusicData.objects.filter(playlist__isnull=True).values( "name").annotate(maxdate=Max("created_on")) But, the problem is along with name and created_on I also need other values like name, url, age, count, playlist__name etc... so I have followed this … -
What would be a minimal example of a Django site that create and deliver a file?
I wrote my first script a few weeks ago after learning Python. Now I have to make it available on a webserver. For that I plan to use Django. I could use Flask for something this small but I have to learn Django anyway. The script currently runs on Google Colab's Jupyter and generate an Excel file with data extracted from an API. It ends by: workbook = xlsxwriter.Workbook(report_name) ... workbook.close() files.downlad(my_file) I have to make a Django app that display : a button to generate and download the file a list of recently generated files with a download link I don't find the documentation to be so clear. It is focused on uploading files with forms. I get that I have to create a file object in model.py and to list existing objects in the template with a for loop. What is less clear is how to save the generated output in a file object. -
The form in which the Boolean Field field must always be true. Django
I am trying to add a restriction so that the user always selects the checkbox to 'True'. It looks like that, but unfortunately it does not work properly. Any help will be appreciated. models.py class OrderingMassage(models.Model): website_rules = models.BooleanField(default=None, blank=True) forms.py class OrderingMassageForm(forms.ModelForm): class Meta: model = OrderingMassage fields = ('website_rules') def clean_website_rules(self): data = self.cleaned_data['website_rules'] if data == None: raise forms.ValidationError("please accept the rules of the website") else: return data -
Form filter database results on same page
I currently have a page that I want to display available lessons. To achieve this I believe I need a form that searches my Lesson model to find a lesson that matches the inputs in the form. I then want the results from that filter to be displayed in a table I have created. I am unsure about the correct way to filter results based on my form inputs and would appreciate some suggestions on that. An example of what I am looking for is if in the form a person enters the value cello for instrument input, beginner for level input, and 2019-02-02 for date input, I want the form on submit to search my lessons in database for one that has lesson_instrument == cello, lesson_level == beginner, lesson_datetime_start == 2019-02-02, and then display that lesson in my table. I have attached my code below for help. <!-- Form --> <form action="{% url 'view:profile' user.id %}" method="POST" autocomplete="off"> {% csrf_token %} <h5>Book a Lesson</h5> <!-- Instrument --> <div class="form-group" name="instrument" id="instrument"> <label>Choose instrument</label> <select class="form-control"> <option value="">Instrument</option> <option value="Cello">Cello</option> <option value="Clarinet">Clarinet</option> <option value="Drums">Drums</option> <option value="Flute">Flute</option> <option value="Guitar">Guitar</option> <option value="Piano">Piano</option> <option value="Saxophone">Saxophone</option> <option value="Violin">Violin</option> <option value="Vocal">Vocal</option> <option value="Trumpet">Trumpet</option> </select> </div> … -
"django.db.utils.IntegrityError: FOREIGN KEY constraint failed" raised while running Behave tests using django-behave
This is a Django project (django=2.1.7, python3.7, django-behave==0.1.6) and all tests run successfully until I add django-behave to run BDD style tests using behave. I have set: TEST_RUNNER = 'django_behave.runner.DjangoBehaveOnlyTestSuiteRunner' and when I run the tests using ./manage.py test, Behave tests run successfully. Nonetheless, I receive a "django.db.utils.IntegrityError" exception when it tears down the test database. The same happens with another Django Behave integration library, behave-django. The step implementation is empty. Following is the stacktrace: Feature: Partnership Tests # flipr/features/affiliate.feature:2 Scenario: Create a New Story with affiliate ID # flipr/features/affiliate.feature:3 Given We create the partner with name "Test Partner" # flipr/features/steps/affiliate.py:6 1 feature passed, 0 failed, 0 skipped 1 scenario passed, 0 failed, 0 skipped 1 step passed, 0 failed, 0 skipped, 0 undefined Took 0m0.000s Error Traceback (most recent call last): File "/Users/fnegarestan/Documents/GitHub/flipr/venv/lib/python3.7/site-packages/django/db/backends/base/base.py", line 239, in _commit return self.connection.commit() sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/fnegarestan/Documents/GitHub/flipr/venv/lib/python3.7/site-packages/django/test/testcases.py", line 209, in call self._post_teardown() File "/Users/fnegarestan/Documents/GitHub/flipr/venv/lib/python3.7/site-packages/django/test/testcases.py", line 908, in _post_teardown self._fixture_teardown() File "/Users/fnegarestan/Documents/GitHub/flipr/venv/lib/python3.7/site-packages/django/test/testcases.py", line 943, in _fixture_teardown inhibit_post_migrate=inhibit_post_migrate) File "/Users/fnegarestan/Documents/GitHub/flipr/venv/lib/python3.7/site-packages/django/core/management/init.py", line 148, in call_command return command.execute(*args, **defaults) File "/Users/fnegarestan/Documents/GitHub/flipr/venv/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, … -
Capturing an ID hidden inside Leaflet popup on click requires two clicks to update [Javascript]
I have a really annoying issue with javascript in my Django project. Currently building a webbapp which reads data from sensors placed in manholes for water-temperature measurements. We display these sensors as markers on a Leafletmap with the pipe-system between each manhole. I'm currently storing the sensor-id as a hidden variable in each manhole and then grabbing these to build a D3 graph displaying the temperature data for the specific manhole that has been clicked. onEachFeature: (feature, layer) => { for (let i = 0; i < place.length; i++) { if (place[i].fields.pnamn === feature.properties.pnamn) { sensorid = place[i].fields.eui; } } var popupText = "<strong>" + feature.properties.pnamn + "<p id='popupText' style='display:none'>" + sensorid + "</p>" + "</strong>"; layer.bindPopup(popupText); }, [......] }).on('click', onClick).on('popupclose', startZoomer).addTo(map); The id in question is the sensorid in the p-element. It works as it should, except for the extremely annoying fact that you can just click on a new manhole to update the graph without clicking twice on the new one or by clicking anywhere on the map. I capture the sensorid in the function below and this is where I believe the problem is hiding. Can't really wrap my head around why this is happening and would …