Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't Install Django Pachages in Heroku
I just deployed my app to Heroku and I am getting an error when opening the application, it says: "ModuleNotFoundError: No module named 'crispy_forms'" and the same for MultiSelectField. I have tried to install these packages in the console at the platform, but it seems to have no effect, every time I run 'heroku run pip freeze' I get the same packages. I have tried to do this in my local console running the following commands: heroku run bash pip install django-crispy-forms pip install django-multiselectfield pip freeze # To check if the packages where installed Then I get that everything seems fine, django-crispy-forms and django-multiselectfield appear in the packages list in the 'pip freeze' command, but when I check in the platform, the updates are not there. What am I doing wrong to install these apps, should I make any sort of save command? -
How can I expire entries to Django database cache?
I have a Django application with a registered database cache: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'exchange_rate_cache', } } I want the entries in my cache to expire and be deleted after a week. To delete an entry from the cache all that is needed is the following: from django.core.cache import cache cache.delete(key) However I mus tonly perform this if the entry has been stored in cache for longer than 1 week. How can this be done? Thank you. -
Using `limit_choices_to` on a FK causes `MultipleObjectsReturned` error on ModelForm submission
TL;DR : Filtering a queryset according to a related object's value may cause duplicate values in the result. This behaviour spreads on the limit_choices_to FK's attribute in a model field when using it in a similar way, possibly causing a MultipleObjectsReturned error when using a modelform associated with this model. Is it possible to apply distinct() or equivalent on a model's foreign key's limit_choices_to in order to avoid duplicate in the options of a modelform's field? Reproducing the problem : With python manage.py shell (and solving it) : Let two models A and B: class A(models.Model): pass class B(models.Model): a = models.ForeignKey(A) d = models.BooleanField(default=False) and the following entries : >>> a = A.objects.create() >>> b1 = B.objects.create(a=a, d=True) >>> b2 = B.objects.create(a=a, d=True) The following queryset using a get() causes an error : >>> A.objects.filter(b__d=True).get(id=1) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/vmonteco/.venvs/django/lib/python3.6/site-packages/django/db/models/query.py", line 384, in get (self.model._meta.object_name, num) app.models.MultipleObjectsReturned: get() returned more than one A -- it returned 2! Which sounds normal since a is present twice in the queryset's result : >>> A.objects.filter(b__d=True) <QuerySet [<A: A object>, <A: A object>]> This error can be solved easily with a simple distinct() : >>> … -
DRF nested-relationships : related_name argument
In DRF documentation: You'll normally want to ensure that you've set an appropriate related_name argument on the relationship, that you can use as the field name. If you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the fields argument. My Room model has the following : hotel = models.ForeignKey(Hotel, related_name="%(class)s_rooms",verbose_name=u'Hotel') How to add this to the Hotel serializer? I tried fields = ('room_set', ...) but I get ImproperlyConfigured at /api/hotel/ Field name room_set is not valid for model Hotel. -
Working of django-allauth
I am new to django-allauth. I wanted to know how are urls for google/ facebook, etc. are generated. I went through the source code but, was not able to completely understand the working it. If I were to reproduce the same url how can I do so? Requesting your reply at the earliest. -
How to have django-allauth only generate necessary table columns when login via email
Currently, we would like to let user Login via email and password Login via Google The implementation of this project pretty much suit our requirement. https://github.com/wsvincent/djangox However, when we exam the generated DB table, it contains a lot of unnecessary fields id | password | last_login | is_superuser | username | first_name | last_name | email | is_staff | is_active | date_joined We refer to this example too https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#a-full-example It allows Login via email and password (But not with Google) The generated table is pretty minimalist id | password | last_login | email | is_active | is_admin We tried to replace custom user model (inherited from AbstractUser) from djangox with custom user model (inherited from AbstractBaseUser) from official Django guideline. However, we get the following error django_1 | Traceback (most recent call last): django_1 | File "manage.py", line 15, in <module> django_1 | execute_from_command_line(sys.argv) django_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line django_1 | utility.execute() django_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django_1 | django.setup() django_1 | File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup django_1 | apps.populate(settings.INSTALLED_APPS) django_1 | File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 120, in populate django_1 | app_config.ready() django_1 | File "/usr/local/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 24, in ready django_1 | self.module.autodiscover() django_1 … -
django api not update data on database
I want to update data on database using django, this is my simple api : class TitleAsDone(APIView): """ this api mark as done published on youtube title """ def post(self, request): #todo: neeed sterilize data title = VideosModel.objects.get(pk=request.data.get('video_id')) if title: title.publicato = True title.youtube_url = request.data.get('youtube_url', None) title.save() #print("debug", title.id) return Response(request.data, status=status.HTTP_201_CREATED) return Response(status=status.HTTP_404_NOT_FOUND) this is my request code : import requests server = "http://bulkvideo.online" #server = "http://localhost:8000" def check_mark_as_done(title_id): data = { "video_id": 5, "youtube_url": "http://youtube.com/ff158P1e4B4", } r = requests.post(f"{server}/api/titles/video/done", json=data) print(r.text) print(r.status_code) check_mark_as_done("151") system return status code 201 created but not change status of item 151 from database, where i wrong ? How i can fix this problem ? my full code application : https://github.com/scaltro/youtubeapp/blob/master/myupload/views/view_titles.py -
What is the best index for postgresql timestamp
I have searched a lot but has not found the answer for the following question. I have a table with lots of record (in the order of 100M) and I want to run the following query on it : Entity.objects.filter(creation_time__gte=some_date).order_by('id').all()[0] and my table is something like follows : class Entity(models.Model): creation_time = models.DateTimeField(null=True, blank=True) # Other fields -
Auth0 - Django and Graphene
Im currently using Graphql with Django Graphene JWT. Im using django for the backend. All requests are authed by the token shown below: I have a schema that creates auth tokens for graphql that currently looks like this: class Mutation(accounts_manager.schema.Mutation, device_manager.schema.Mutation, graphene.ObjectType): token_auth = graphql_jwt.ObtainJSONWebToken.Field() verify_token = graphql_jwt.Verify.Field() refresh_token = graphql_jwt.Refresh.Field() Im trying to find documentation and also understand how this will work. I have a reactjs webapp that currently connects to the graphql api and now I am also building a react native app to connect to it too. They way I see it is that Auth0 only keeps a token per user that then is used through graphql to be authed to django? Im a little lost about how it should all work! -
Searching priorities with django rest framework
I have a table with the following entries 200 tomatoes bunch a tomato soup tomato etc. Now when the user searches for tomato I'd like to return the exact match - tomato result first and the other ones alphabetically ordered next. I'm using SearchFilter and search_fields = ['name'] in my DRF API view. Is there a way to customise the search like that? Do I need to override how the SearchFilter filters the queryset? I'd also like to retain the default behavior of using search_terms so when user searches for soup tomato the search would return tomato soup. -
Django ModelForm Foreign Key Dropdown passes __str__ but stores fkey_id
There are two models and I would like to store a column field from one model to another model. models.py: class Company(models.Model): name = ... def __str__(self): return self.name class Rate(models.Model): company = models.ForeignKey(Company) currency = ... name = ... def __str__(self): return self.name + " " + self.currency class Client(models.Model): name = ... currency = .... company = models.ForeignKey(Company) base_rate = models.ForeignKey(Rate) def __str__(self): return self.name forms.py: class ClientForm(forms.ModelForm): class Meta: model = Client fields = ( "name", "company", "base_rate", ) views.py: class ClientCreateView(FormView): template_name = "client/new_package.html" form_class = ClientForm success_url = reverse_lazy("home") def form_valid(self, form): detail = form.save(commit=False) base_rate_id = form.cleaned_data['base_rate'] detail.currency = Rate.objects.values_list("currency", flat=True).filter(base_rate_id=base_rate_id) detail.save() if detail is not None: return redirect('display_package' , detail.id) else: return super(ClientCreateView, self).form_valid(form) Basically, I want selected currency value to be saved in my client model from Rate model. Any help will be appreciated as from cleaned data I am getting str returned value instead of selected option id value (i.e. str from client model ). -
Running python scripts on apache server and get the output as http response
I have a django website hosted on raspberry pi using apache server. Is there any way I can execute python scripts on the pi server and get the output of the scripts in the website? I have link to all the python files on the website but when I click them instead of executing the raw code opens. -
How to add 'id' to the fields in HyperlinkedModelSerializer in DRF
When using the HyperlinkedModelSerializer from Django REST Framework, the field id is not included in the fields by default. This question has an answer that explains that well. However I have a problem I'd like to solve in a particular way. I have a model with custom ID and few dozens of other fields: class Foo(models.Model): id = models.IntegerField(primary_key=True) # 20-30 fields In the serializers.py I'd like to include all fields from the model: class FooSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Foo fields = '__all__' However this doesn't include the field id. Defining id = serializers.ReadOnlyField() doesn't help me either, as id shoud be editable. Specifying all the fields manually like this: fields = ('id', # all other fields) would be a solution I'm trying to circumvent because the model class has a lot of fields and they might change in future. Is there an elegant possibility to add the field id? Maybe overriding the __init__ method? -
Django CMS: BadMigrationError while migrating djangocms_table in version 3.5.2
I want to install djangocms_table plugin.My current Django cms version is 3.5.2 I followed the below steps to do the same. 1.pip install djangocms_table 2.Added 'djangocms_table' to INSTALLED_APPS 3.manage.py migrate djangocms_table After I ran migrate command got the below exception. System check identified some issues: WARNINGS: ?: (1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your default TEMPLATES dict: TEMPLATE_DIRS. Traceback (most recent call last): File "/host/lendingstream/src/web/ConsumerUI/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 25, in handle call_command("migrate", **options) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command return command.execute(*args, **defaults) File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 93, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/usr/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 19, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 47, in __init__ self.build_graph() File "/usr/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 182, in build_graph self.load_disk() File "/usr/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 123, in load_disk "creating Django migrations." % app_config.label django.db.migrations.loader.BadMigrationError: Migrated app 'djangocms_table' contains South migrations. … -
in django dynamic view how to create a download link and assign a file to the download link in run time
I am new to django. could any one let me know how to assign a file to a anchor tag in django template. enter image description here -
setting up different messages on making a booking according w.r.t chosen date and not accepting booking for the same day after a fixed time
i've all models and views ready for accepting bookings, i'm currently facing a major roadblock. There are two cases in which i want to return a success/info message: 1: when a booking is initiated for same day i want to restrict same day booking time to 2:00 pm and when a booking is initiated after 2:00 pm i want give a message that booking will be treated for the next day. 2: whenever a booking is initiated for a future date irrelevant of the time a success message for the same should be displayed for date-input i'm using datepicker. and for time i have divided time slots and taken them into a choicefield. each booking has a 90 minutes gap so options for the choicefield goes like this: TIME_CHOICES = ( ('10:00','10:00 to 11:30'), ('11:30','11:30 to 1:00'), ('13:00','1:00 to 2:30'), ('14:30','2:30 to 4:00'), ('16:00','4:00 to 5:30'), ) #form_field: time_slot = forms.ChoiceField( choices=TIME_CHOICES, widget=forms.Select(attrs={'class':'form-control fc'})) i've also tried something like this in my views: booking_date=request.POST.get('booking_date') # datepicker. curr_time = time.strftime("%H:%M:%S") print(curr_time) date = datetime.strptime(str(dt.datetime.now().date())+" "+str(curr_time),'%Y-%m-%d %H:%M:%S') deadline_time = datetime.strptime(str(booking_date)+" "+'14:00:00', '%Y-%m-%d %H:%M:%S') print(date) print(deadline_time) if date >= deadline_time: messages.info(request,"MY_MESSAGE_1", extra_tags='alert') return HttpResponseRedirect(redirect_to='/home') else: # other message return HttpResponseRedirect(redirect_to='/home') -
Cannot create django test database
I have a projects with hundreds of migrations. When I try to run the tests it gives me the stacktrace: ./manage.py test Creating test database for alias 'default'... Traceback (most recent call last): File "/project/lib/python3.5/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) File "/project/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 326, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: near "USING": syntax error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/project/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/project/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/project/lib/python3.5/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/project/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/project/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/project/lib/python3.5/site-packages/django/core/management/commands/test.py", line 62, in handle failures = test_runner.run_tests(test_labels) File "/project/lib/python3.5/site-packages/django/test/runner.py", line 601, in run_tests old_config = self.setup_databases() File "/project/lib/python3.5/site-packages/django/test/runner.py", line 546, in setup_databases self.parallel, **kwargs File "/project/lib/python3.5/site-packages/django/test/utils.py", line 187, in setup_databases serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True), File "/project/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 69, in create_test_db run_syncdb=True, File "/project/lib/python3.5/site-packages/django/core/management/__init__.py", line 131, in call_command return command.execute(*args, **defaults) File "/project/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/project/lib/python3.5/site-packages/wagtail_modeltranslation/management/commands/migrate_translation.py", line 25, in handle super(Command, self).handle(*args, **options) File "/project/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/project/lib/python3.5/site-packages/django/db/migrations/executor.py", line 115, in … -
Filtering using __range on a datetimefield
I have read and try so many tactics to make __range inclusive. Please can someone help out here views.py def generate_report(request): if 'start_date' and 'end_date' in request.GET: account_type = AccountUser.objects.get(user_id=request.user.id) query_string_start = request.GET.get('start_date') query_string_end = request.GET.get('end_date') search_query = BedAllotment.objects.filter(hospital_id=account_type.hospital_id, departure_date__gte=query_string_start, departure_date__lte=query_string_end).order_by('-departure_date') return render (request, 'report/report_preview.html', {'account_type':account_type, 'query_data':search_query, 'query_string_start': query_string_start, 'query_string_end':query_string_end}) I will like to include all query instance on the end_date. Please Help -
How to create/define GeoPoint in Django by django-elasticsearch-dsl?
How to create/define GeoPoint in Django by django-elasticsearch-dsl? I have already a bid DB in this DB I have defined fields latitude and longitude. I want to create a search by radius but don't understand how to create GeoPoint for my search by radius. Do I need to create new GeoPoint field for this search or maybe I can use raw fields latitude and longitude? I already defined DocType Land model with fields latitude and longitude but how to create from this fields GeoPoint? Thanks! -
rsvp list in django
For a Django Application, I am attempting to make an RSVP list. The issue I am having is that in the admin page, I would like it to show all users that have been created in the User model, whether they have RSVP'd or not. At the moment I can only get it to show users that have RSVP'd. home/models.py class rsvpList(models.Model): choices = ( ('Yes','Yes'), ('No','No'), ('No Response','No Response') ) plusOnes = ( ('0','0'), ('1','1'), ('2','2'), ('3','3'), ('4','4'), ) user = models.ForeignKey(User, on_delete='cascade') choice = models.CharField(max_length=11, choices=choices, default='No Response') additional = models.CharField(max_length=1, choices=plusOnes, default='0') def __str__(self): return str(self.user) If the user has RSVP'd, I would like it to show the 'yes' or 'no' value. However, if I am awaiting a response, I would like the 'No Response' value to show. Thank you in advance. -
Django: TypeError: '<' not supported between instances (model objects)
I'm trying to migrate my Django project from Python 2.7/Django 1.11 to Python 3.7/Django 2.1. I've found one issue and I want to understand its cause. I have 3 models in my project: class DeviceModel(models.Model): name = models.CharField(max_length=255) pirsh = models.CharField(max_length=255) def __str__(self): return self.name + " - " + self.pirsh class Device(models.Model): created_at = models.DateTimeField(auto_now_add=True) device_model = models.ForeignKey(DeviceModel, on_delete=models.CASCADE) serial_number = models.CharField(max_length=255) def __str__(self): return self.device_model.name + " - " + self.device_model.pirsh + " - " \ + self.serial_number class DeviceTest(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE) created_at = models.DateTimeField() TEST_OK = '+' TEST_ERROR = '-' TEST_PENDING = '?' TEST_RESULT_CHOICES = ( (TEST_OK, 'Success'), (TEST_ERROR, 'Fail'), (TEST_PENDING, 'Not checked'), ) status = models.CharField(max_length=1, choices=TEST_RESULT_CHOICES, default=TEST_PENDING) comment = models.TextField(blank=True, default="") tester = models.CharField(max_length=255) action = models.CharField(max_length=255) def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.created_at: self.created_at = timezone.now() return super(DeviceTest, self).save(*args, **kwargs) def __str__(self): return self.device_id.device_model.name + " - " + \ self.device_id.device_model.pirsh + " - " + \ self.device_id.serial_number + " - " + \ str(self.created_at) + " - " + \ "Result (" + self.status + ")" And this is my code to sort Device objects by latest test status ('dev_filter', 'field' and 'order' parameters are … -
Limit queryset on Django 2 autocomplete_field
For a long time we've been overriding our ModelAdmin's formfield_for_foreignkey to limit the queryset the field can choose from. Here's a simplified version of what I mean: def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "site": if not request.user.is_superuser: kwargs["queryset"] = request.user.site But I recently added this field to the autocomplete_fields definition (to get some Select2 gravy). The result was I now see no suggestions as a non-superuser account. Is there a more right way to limit the queryset, or is this a simple bug in Django? -
How to convert the input text into image with a background in django python
I want to convert the text into image in django for example If I entered a text SAMPLE it should converted into an image format with background of our own . I need this to be done with django python. -
How to make django embedded forms
I come from Symfony world and I don't understand Django forms. In Symfony, we can embed form as field of an another form. It's usefull to save at once an object and related objects. Imagine that we have these models: - Language - Post (with an image field called "image") - PostTranslation (with "post_id" and "language_id", and "title", the field to be translated) There are two languages (French and English) and when we go on create view, I'd like to see one form with an upload field for image and two fields for title (one for French and one for English). When I submit the form, data must be validated and saved in database. When we go on the update view, we can see the image field, and the two title fields, all populated with database value. But, if in the meantime we added a language (Spain for exemple) (on an another CRUD for languages), we could see an third title field (blank) for this language, that it must be saved on form submission. It's as simple as f**k to do that in Symfony, but, how to do that in Django ? I don't find an easy way (even with … -
Using Ajax with Django to call backend and display result
I am taking user input and sending it to Django backend for some text processing. After performing backend operation I want to display results. I tried but as I am new with ajax,I am not sure where I am making mistake. Can anyone please give me correct way of using ajax for this operation? I appreciate if you can give link to any good reference document. Current issue - When I click on submut button it removes input text area. My html report.html - {% extends 'base.html' %} {% block content %} <h1>StopWordsRemoval</h1> <script type='text/javascript'> $(document).ready(function(){ $(form).on('submit', function(event){ $.ajax({ url: 'stopwordsremoval/(?P<document1>.+)' type: 'POST', data: this.serialize(), }); }); }); </script> <div> <form method = "post" > {% csrf_token %} {{ form}} <button type="submit">stopwordsremoval</button> </div> </form> <div > <ul> <li>{{ naturallanguageprocessing }}</li> </ul> <a href="{% url 'stopwordsremoval' %}" </a> <style> div { width: 1000px; border: 5px solid green; padding: 10px; margin: 10px; } </style> </div> </div> {% endblock %} urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'stopwordsremoval/$', views.stopwordsremoval.as_view(), name='stopwordsremoval'), url(r'stopwordsremoval/(?P<document1>.+)/$', views.ReportDetails.as_view(), name='report_details'), ] forms.py from django import forms class ReportForm(forms.Form): #pdb.set_trace() text = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 100}))