Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
If there is 2 exact titles, display it only once
Hello I have got a list that displays titles of items that are displayed on the page(i can filter items by exact title). Some items have the same title, so some titles are displayed more than once. Is there a way to show only one type of title in the list? I am using sqlite, so distinct wont work. views.py def SearchView(request, category_id=None): if category_id: category = Category.objects.get(pk=category_id) item_list = Item.objects.filter(category__id=category_id) else: item_list = Item.objects.all() title = request.GET.get('title') if title: item_list = item_list.filter(title__iexact=title) else: query = request.GET.get('q') if query: item_list = item_list.filter(title__icontains=query) price_from = request.GET.get('price_from') price_to = request.GET.get('price_to') item_list = item_list.annotate( current_price=Coalesce('discount_price', 'price')) if price_from: item_list = item_list.filter(current_price__gte=price_from) if price_to: item_list = item_list.filter(current_price__lte=price_to) context = { 'item_list': item_list, 'category': category, } return render(request, "search.html", context) html template: <ul> {% for item in item_list %} <li> <a href="{% if category %}{% url 'core:category_search' category.id %}{% else %}{% url 'core:search' %}{% endif %}?title={{item.title}}"> {{ item.title }} </a> </li> {% endfor %} </ul> -
ModelMultipleChoiceField raises "Enter a list of values."
I have a form: class BaseCommandForm(forms.Form): devices = forms.ModelMultipleChoiceField( queryset=Device.objects.filter(token__isnull=False).order_by('division__name', 'pk'), widget=forms.Select(attrs={'class': 'devices-list', 'multiple': 'multiple', }) ) def __init__(self, **kwargs): super().__init__(**kwargs) self.fields['devices'].label_from_instance = BaseCommandForm.label_for_device_instance @staticmethod def label_for_device_instance(obj: Device) -> str: return f'{obj.division.name} -> #{obj.pk}' It's rendered as select: <select name="devices" class="devices-list select form-control is-invalid select2-hidden-accessible" multiple="" id="id_devices" data-select2-id="id_devices" tabindex="-1" aria-hidden="true"> <option value="1" data-select2-id="6">Test Division -&gt; #1</option> <option value="2" data-select2-id="7">Test Division -&gt; #2</option> ... </select> My view: class CreateCommandView(CompanyMixin, GroupRequiredMixin, FormView): template_name = 'commands/create.html' group_required = 'company_admin' # TODO: Change group success_url = reverse_lazy('companies:commands:list') def dispatch(self, request, *args, **kwargs): command_type = self.request.GET.get('type') if command_type not in [TYPE_UPDATE_CONFIG, TYPE_SHOW_MESSAGE, TYPE_DOWNLOAD_FILE, TYPE_UNINSTALL_APP, TYPE_WIPE_DEVICE, TYPE_UNINSTALL_AGENT]: return HttpResponseBadRequest() return super().dispatch(request, *args, **kwargs) def get_form_class(self): command_type = self.request.GET.get('type') if command_type == TYPE_UPDATE_CONFIG: form_class = UpdateConfigCommandForm elif command_type == TYPE_SHOW_MESSAGE: form_class = ShowMessageCommandForm elif command_type == TYPE_DOWNLOAD_FILE: form_class = DownloadFileCommandForm elif command_type == TYPE_UNINSTALL_APP: form_class = UninstallAppCommandForm elif command_type == TYPE_WIPE_DEVICE: form_class = WipeDeviceCommandForm elif command_type == TYPE_UNINSTALL_AGENT: form_class = UninstallAgentCommandForm else: raise ValueError(f'Invalid type: {command_type}') return form_class def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['command_type'] = self.request.GET.get('type') return context def form_invalid(self, form): print(self.request.POST) return super().form_invalid(form) def form_valid(self, form): form.save() return super().form_valid(form) I select two values and submit the form: And it returns error: I see only one … -
Django rest API, nested serializer uploading multiple images?
I am pretty stuck working with DRF for the first time. I am looking to upload multiple Images to a single real estate Listing. My image model class Image(models.Model): photo = models.ImageField(blank=True, upload_to=get_image_filename) listing = models.ForeignKey(Listing, on_delete=models.CASCADE) my Image, Listing, and Listing detail serializers class ListingSerializer(serializers.HyperlinkedModelSerializer): image_set = ImageSerializerForListingDetail(many=True, required=False) class Meta: model = Listing fields = ['url', 'address', 'image_set', ] class ListingDetailSerializer(serializers.HyperlinkedModelSerializer): user = AccountSerializer(read_only=True) image_set = ImageSerializerForListingDetail(many=True, required=False) class Meta: model = Listing fields = '__all__' depth = 1 class ImageSerializerForListingDetail(serializers.ModelSerializer): image_url = serializers.SerializerMethodField() class Meta: model = Image fields = ('image_url', ) def get_image_url(self, listing): return listing.photo.url My view class ListingViewSet(viewsets.ModelViewSet): queryset = Listing.objects.all() serializer_class = ListingSerializer detail_serializer_class = ListingDetailSerializer permission_classes = [IsOwnerOrReadOnly, ] '''Show detailed Listing view''' def get_serializer_class(self): if self.action == 'retrieve': if hasattr(self, 'detail_serializer_class'): return self.detail_serializer_class return super(ListingViewSet, self).get_serializer_class() I am having trouble figuring out how to upload multiple Images, to a single Listing, and where to override. I would like it possible when both creating and editing listings. Any help is greatly appreciated. Thanks! -
Django change object details when button is clicked
Good evening! I want to make two buttons, when one is clicked automatically change details of this object. I've already set to view two models but i don't know how to manage change only one post. Whether I should use template tag or try to use JS (which frankly I don't know how to use) Thanks for your replies! views.py class PostList(ListView): template_name = 'post/index.html' ordering = ['-date'] queryset = EveryPostPl.objects.all() def get_context_data(self, **kwargs): context = super(PostList, self).get_context_data(**kwargs) context['EveryPostRu'] = EveryPostRu.objects.all() context['EveryPostPl'] = self.queryset return context html {% extends "post/base.html" %} {% block title %} <title>Home Page</title> {% endblock title %} {% block content %} {% for obj in EveryPostPl %} <div class="card text-center"> <div class="card-header"> <ul class="nav nav-tabs card-header-tabs"> <li class="nav-item"> <a class="nav-link nav-main" href="#">PL</a> </li> <li class="nav-item"> <a class="nav-link nav-main" href="#">RU</a> </li> </ul> </div> <div class="card-body"> <h5 class="card-title"><a href="{% url 'detailpost' obj.pk %}">{{ obj.title }}</a></h5> <p class="card-text">{{ obj.text|truncatechars:350 }}</p> <a href="{% url 'detailpost' obj.pk %}" class="btn btn-dark float-right">Zobacz</a> </div> <div class="card-footer text-muted"> <span class="float-left">{{ obj.date|date:"d M y" }}</span> <span class="float-right">Przesłane przez: {{ obj.User }}</span> </div> </div> {% endfor %} {% endblock content %} enter image description here -
how i do consume a rest api with python
i have the next api Rest which I want to consume from python and get the answer and show it to the client from my site { "info": { "_postman_id": "9fbc51ae-b42d-46f5-b919-507d9a0339df", "name": "NRWebApi_SiepPrueba", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, "item": [ { "name": "Documents_Document", "request": { "method": "POST", "header": [ { "key": "Content-Type", "name": "Content-Type", "value": "application/json", "type": "text" } ], "body": { "mode": "raw", "raw": "{\n \"Key\": \"*****\",\n \"Secret\": \"*****\",\n \"Filters\": {\n \"DocumentoTipoEstandar\": \"facturadeventa\",\n \"DocumentoNumeroCompleto\": \"SETT109\"\n }\n}" }, "url": { "raw": "https://www.numrot.net/NRWApiPrueba/api/Documents/Find", "protocol": "https", "host": [ "www", "numrot", "net" ], "path": [ "NRWApiPrueba", "api", "Documents", "Find" ] } }, "response": [] } ], "event": [ { "listen": "prerequest", "script": { "id": "4bc40342-a4ee-43c7-800e-ff19e013c8a9", "type": "text/javascript", "exec": [ "" ] } }, { "listen": "test", "script": { "id": "2135a97a-5ab3-4d79-89d8-0e9743d935b5", "type": "text/javascript", "exec": [ "" ] } } ], "protocolProfileBehavior": {} } when the postman process brings me the answer, how do I get that result from python when the postman process brings me the answer, how do I get that answer in python code ATTEMPT WITH THIS CODE import requests import json if __name__ == '__main__': url='https://www.numrot.net/NRWApiPrueba/api/Documents/Find/' args={} headers = {'Content-Type': 'application/json'} body= { "Key": "**", "Secret": "****", "Filters": { "DocumentoTipoEstandar": "facturadeventa", "DocumentoNumeroCompleto": "SETT109" … -
Celery Beat scheduler won't execute my task in Django
I have had some trouble setting up my celery module in Django. Not only am I very confused by the settings requirement, I also have a hard time understanding my errors. I want to run a function at a specific time everyday, something I used to do with crontab. Celery is apparently better suited for this type of tasks, that's why I'm trying to move towards this solution. The set up seems to be okay and I see the celery scheduler run when I invoke it but my task is not processed when the interval kicks in. I saw a lot (!!!) of different set-up for celery so my code might incorporate redundancies and unnecessary lines. The function I want to trigger is called team_accountabillity() and is present in my app "myteam.task.py" I have Celery 4.4.0 and I use rabbitMQ as a queue manager (I have also installed redis because many tutorials went with this one). Here is my proj/settings.py from __future__ import absolute_import import os from datetime import timedelta from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_BEAT_SCHEDULER = { 'team accountability': … -
Showing a Django ForeignKey value in template
I'm a Django noobie and trying to show a model's ForeignKey value in a template, all other fields are showing fine but I could'nt make it work. Here is my code: models.py: class BodyPart(models.Model): body_part = models.CharField(max_length=20, unique = True) class Exercise(models.Model): body_part = models.ForeignKey(BodyPart, on_delete=models.CASCADE, default = "bodypart", related_name="bodypart") views.py: exercises = Exercise.objects.filter(category=exercisedetailcategory).values() context = { "exercises" : exercises, } return render(request,"exercises-categories.html",context) template : {% for exercise in exercises %} <span class="post-meta-category"><a href="">{{exercise.body_part}}</a></span> <div class="post-item-description"> <a href="">{{exercise.title}}</a> <p>{{exercise.content}}</p> {% endfor %} I tried to solve it by looking at the similar questions but none of them worked for me. Do you have any suggestions? -
How to link wsgi.py to your domain and hosting?
import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Nametag.settings') application = get_wsgi_application() Anybody Help me! . I did not find solution how to link -
Django vs Node.js
This may be off-topic. But, please do not close it before answering. I am new to web development and I have learned front end technologies like Bootstrap, CSS, HTML, etc. I am getting into the server-side now, but I am not able to decide which one to go for? Node.js or Django? How do I choose? I want something simple to code in and easy to use. I have done thorough reading on this topic but could not come up with 'what technology I should use'. -
django oscar custom benefit recursion
i created a custom benefit, but when that offer added to basket, apply method run in recursively and its not working class ProductPackageOfferBenefitFixed(Benefit): ''' oscar_customize.offer.models.ProductPackageOfferBenefitFixed ''' @property def name(self): return "Product Package Benefit" @property def description(self): return "ProductPackageOfferBenefit Absolute or Presentage" class Meta: proxy = True def apply(self, basket, condition, offer): return BasketDiscount(Decimal('10')) def apply_deferred(self, basket, order, application): return BasketDiscount(Decimal('10')) -
Using `search=term1,term2` to match multiple tags for the same object using DRF
I'm uplifting an old codebase to recent versions of Django and Django Rest Framework, but I've run into a hard wall around how the ?search=... filter works when using multiple terms in recent versions of Django Rest Framework. Up until DRF version 3.6.3 it was possible to do a ?search=term1,term2 endpoint request and have DRF return objects with many-to-many relations in which both search terms matched the same field name, e.g if the model had a many-to-many field called tags relating to some model Tag, then an object with tags cake and baker could be found by DRF by asking for ?search=cake,baker. In the codebase I'm uplifting, the (reduced) code for this looks like: class TagQuerySet(models.query.QuerySet): def public(self): return self class Tag(models.Model): name = models.CharField(unique=True, max_length=150) objects = TagQuerySet.as_manager() def _get_entry_count(self): return self.entries.count() entry_count = property(_get_entry_count) def __str__(self): return str(self.name) class Meta: ordering = ['name',] class EntryCustomFilter(filters.FilterSet): tag = django_filters.CharFilter(name='tags__name', lookup_expr='iexact', ) class Meta: model = Entry fields = [ 'tags', ] class EntriesListView(ListCreateAPIView): """ - `?search=` - Searches title, description, and tags - `&format=json` - return results in JSON rather than HTML format """ filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter, ) filter_class = EntryCustomFilter search_fields = ('title', 'description', 'tags__name', ) parser_classes … -
Implementing web api app and token based session management using pure django
I am new to django and trying to implement web api app using django. Most of the google search results is using DRF(Django Rest Framework). Right now I am learning django. And I am not interested in using DRF or any third party django app. Once I have a good understanding of django I will learn and try third party django packages. For my app I am using a custom user inheriting from AbstractBaseUser. I have been able to successfully verify user phone via otp. Implementation is rudimentary. But it works. I did not use any third party app for implementing OTP verification. I did search for otp verification on google. Again all the results were dominated by third party apps. I want user to login using android app. Android or any other app will communicate using my web api. How do I go about having a token based session management using pure django(no third party apps.)? Can the standard django session be used? I want to convert my webapp to web api app. It will be great if you can provide any pointers or good resource on implementing web api using pure django. PS: I am fed up with … -
How remove double quotes from postgres table and field names on django?
I'm working on a django project with postgres where table and field names are generated with double quotes. Anyone knows how can I disable this behavior? [Model definition] class Test1(models.Model): key = models.UUIDField('key', db_column='KEY', editable=False, unique=True, default=uuid.uuid4) name = models.CharField('name', db_column='NAME', max_length=128, null=False) class Meta: db_table = 'Test1' [Migtation] operations = [ migrations.CreateModel( name='Test1', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('key', models.UUIDField(db_column='KEY', default=uuid.uuid4, editable=False, unique=True, verbose_name='key')), ('name', models.CharField(db_column='NAME', max_length=128, verbose_name='name')), ], options={ 'db_table': 'Test1', }, ), ] [DDL Generated] create table "Test1" ( id serial not null constraint "Teste4_pkey" primary key, "KEY" uuid not null constraint "Teste4_KEY_key" unique, "NAME" varchar(128) not null ); alter table "Test1" owner to postgres; [DDL Expected] create table Test1 ( id serial not null constraint "Teste4_pkey" primary key, KEY uuid not null constraint "Teste4_KEY_key" unique, NAME varchar(128) not null ); alter table "Test1" owner to postgres; [requirements] django==2.1.10 django-choices==1.6.1 django-cors-headers==2.4.0 django-environ==0.4.5 django-extensions==2.1.4 djangorestframework==3.8.2 django-filter==2.0.0 drf_yasg==1.14.0 ruamel.yaml==0.15.100 drf-nested-routers==0.91 dj-database-url==0.5.0 requests==2.22 whitenoise==4.1.3 dry-rest-permissions==0.1.10 django-polymorphic==2.1.2 psycopg2==2.7.0 elastic-apm==4.2.2 brutils==1.0.1 Jinja2==2.10.3 schedule==0.6.0 pika==1.1.0 python-jose==1.4.0 -
Passing HTML form variable to python function in Django
I'm extremely new to Django, but I have been trying to figure out the solution for hours. I want to pass a variable from a html form to the backend and then use the variable there to make an api request. I want the API result to be showing on the html file as well as it being checked against a list(in the backend) and having the result from the comparison on the html file as well. I would like onClick of submitting the variable on HTML (which is a email) that everything works without having multiple buttons/form. I believe I have multiple errors. Any help is greatly appreciated. index.html <body> <form action="#" method="post"> <input type="text" class="form-control" id="emailvalue" placeholder="" value=" "name="emailvalue"> <input type="submit" value="Submit" onclick="location.href={% url 'script' %}"><hr> The Associated IP addresses are: {% for j in nonduplicate_list %} <li>{{j}}</li> {% endfor %} <hr> The unblocked IP addresses are: {% for i in unblocked_ip %} <li>{{i}}</li> {% endfor %} </form> </body> views.py def get_ip(request): if request.method == 'POST': input_email = request.POST.get('emailvalue') three_days_ago = datetime.datetime.now() - datetime.timedelta(days = 30) time_in_format = three_days_ago.strftime('%Y-%m-%dT00:00:00.000Z') security_domain = 'https://security.com/api/v1/logs?' + 'q=' + input_email + '&since=' + str(time_in_format) print(security_domain) r = requests.get(security_domain) data = json.loads(r.content) data1 … -
Django: How to show only the data corresponding to the current user?
I am trying to develop a simple webpage in Django where the users shall be able to create databases via ModelForms and explore only their own created content. They shall not be able to see data created by other users. So far I was not able to realize that, each user is still able to see the data of all other users. In my models.py I linked my database to the User by Foreign Key. I think the problem lies in my view.py but I am somehow stuck.. I would be grateful for any help. Thank you in advance! This is my models.py: from django.db import models from django.contrib.auth.models import User CHOICES = ( ('rent', 'Rent'), ('grocery', 'Grocery'), ('shopping', 'Shopping'), ('gym', 'Gym'), ('phone', 'Phone'), ('freetime', 'Freetime'), ('other', 'Other') ) class UserDetails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="new_spending", null=True) title = models.CharField(max_length=100) notes = models.CharField(max_length=255) expense_name = models.CharField(max_length=255) cost = models.FloatField() date_added = models.DateTimeField() category = models.CharField(max_length=25, choices=CHOICES) def __str__(self): return self.title My forms.py: from django import forms from datetime import date from django.forms import ModelForm from .models import UserDetails class UserModelForm(ModelForm): current_date = date.today() YEARS = [x for x in range(current_date.year - 1, current_date.year + 6)] today = current_date.strftime("%Y-%m-%d") date_added = … -
is there any need to use django forms while using reactjs in the frontend?
I working with Django as backend framework and I wonder if I use reactjs as frontend framework, do I need to use Django forms in the backend (for validation purpose) ? -
Get relationship model name of object Django
I'm trying to get the model name for different objects: This kinda works: last_profile = Profile.object.last() profile.__class__._meta.verbose_name // 'profile' But not this: last_profile_login = ProfileLogin.objects.last() last_profile_login.__class__._meta.verbose_name // 'profile login' I would like the last example to be profile_login. The reason, I'm doing this is to create a dynamic query using filter(). -
List of list of objects python django rest framework
Need to create List of list of class objects and return the list in python django rest framework. Sample output:- [ { "SectionName": "Header", "SectionOrder": 0, "Fields": [ { "ID": 0, "Order": 1, "Name": "ID" }, { "ID": 0, "Order": 2, "Name": "sub date" } ] }, { "SectionName": "Notes", "SectionOrder": 1, "Fields": [ { "ID": 1241, "Order": 3, "Name": "comments" }, { "ID": 9658, "Order": 4, "Name": "workers" } ] }, { "SectionName": "Distribution", "SectionOrder": 2, "Fields": [ { "ID": 5248, "Order": 5, "Name": "reports" } ] } ] -
Issue accessing a (django) app in a vagrant box with ssl / nginx /gunicorn
I'm using Ansible to deploy a django/react app. I'm deploying it on a development Digital Ocean server and everything is working well on that side. I'm using a similar process to deploy it on a Vagrant box... this is were I'm having troubles. I'm having issues to access the app on the vagrant guest machine from the host. I detail below the configuration (vagrant, nginx files). When I access a url like 127.0.0.1:8443/time-series/, nginx is responding with 400 Bad Request The plain HTTP request was sent to HTTPS port. However when I access the url 127.0.0.1:8080/time-series/, I have a response This site can’t be reached tsango’s server IP address could not be found. So it seems that nginx is reached, but cannot serve the app files. I created ssl crt/key for localhost using let's encrypt certificate for localhost web page. What do you think can be wrong in what I did? Also what is the good approach to debug such an issue? The Vagrantfile is: # -*- mode: ruby -*- # vi: set ft=ruby : # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "ubuntu/bionic64" config.ssh.forward_agent = true config.vm.define … -
Django: built in User with ManyToMany
in my app I have built in User which is created during register. After that, User can add URL to database. So User can have multiple URLs and vice versa. in models.py I have from django.db import models from django.contrib.auth.models import User class Repository(models.Model): url = models.CharField(max_length=250,unique=False) user = models.ForeignKey(User,related_name='user',on+delete=models.CASCADE,default='') repositorys = models.ManyToManyField(User,related_name='users') in my views.py url = request.session.get('url') repo = Repository(url=url,user=request.user) repo.save() And my questions: 1) How can I check user's repos in shell? Should I import django.contrib.auth.models.User? 2) When Im looking at admin page and Repository table I can see that Repositorys column has 2 values: admin and user, despite of fact, that I added this url while being logged as admin, but value in user column is correct -
Django use the current url parameters to pass it to a form
I need to use the current url parameters and pass it to a form. The thing is that I'm displaying the results in a table using Dango-tables2 so I want to add a payemnt to that specific results using the 'Agregar Pago' button I have tried with no luck to get the values '1' and '2020-W08' so I can initialize the form with the fields: carro = 1 semana = 2020-W08 and the other fields ready for the user to type the values. So the user only enters the values and are applied to that specifica carro and semana. in my html tag I have tried: <a href={% url 'pagoaexistente' request.get_full_path %}><button type="button" class="btn btn-primary" > but it gives me the complete path in 1 argument which is not what I want. I have not found a way to get those two values from the table, let's say from the firs row get carro and semana, but I feel that is not correct to do it that way. -
Dynamic Django query using filter()
I created a function that takes an object, and what I would like to do is be able to filter by this obj and delete the queryset result. I tried this, but it doesn't work. def delete_profile_from_obj(obj): model = model_obj.__class__._meta.model_name profiles = Profile.objects.filter(Q(model=obj)) profiles.delete() Is there a way to make this dynamic, so I can pass any obj that has a relationship with Profile Also model_obj.__class__._meta.model_name works when finding the name of a word model such as Profile, but if I have a model called: ProfileLogin, the result will be profilelogin, but it should be profile_login. -
django - template rendering html according to db table value with no defaults
I'm working on a doodle like page where you could check and uncheck time options when you can attend a specific event. I try to render my page that will go through the users and the event timeframes and print a checked or unchecked checkbox. The problem is that by default there is no record connecting the user, event and time. So I can't tell while rendering whether I found a record or not. As far as I know I can't use a variable to keep track of the record mentioned above. This leads to an issue of having both checkboxes or no checkboxes for time slots that have no record. This is my template html: {% for participant in participants %} <tr> <td>{{ participant.name }}</td> {% for options in polltimes %} <td> {% for avail in availability %} {% if avail.polltime_id == options.id %} {% if avail.availability == "1" %} <input type="checkbox" name={{options.id}} checked> {% endif %} {% if avail.availability == "0" %} <input type="checkbox" name={{options.id}} > {% endif %} {% endif %} {% endfor %} </td> {% endfor %} </tr> {% endfor %} Now this might be a bad approach due to having too much logic in the … -
Error to run python manage.py migrate_schemas (django-tenant) into VPN
I have a single django application hosted on AWS - Web client <=> nginx <=> uwsgi <=> django. I decided to transform It into a multi tenant with django-tenant. Also, I'm using django-celery-beat for scheduling tasks. My single application works normally on AWS and my multi tenant works locally too, in my machine. I had a problem recognizing the schemas with celery, but I solved It here: Is It possible to user django-celery-beat with django-tenant?. However, the error I'm getting now is within my VPN: django.db.utils.ProgrammingError: relation" app_modelcustomuser "does not exist It appears when I try to run ./manage migrate_schemas (I do makemigration in my local machine and commit It, so I just need to migrate to the DB in my VPN) or any other migrate. I tried to migrate by application and I get It when I do ./manage migrate admin. My settings.py file looks like this: SHARED_APPS = [ 'django_tenants', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'clients', ] TENANT_APPS = [ 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', # Libs 'stdimage', 'django_celery_beat', 'djcelery_email', 'tenant_schemas_celery', # 'widget_tweaks', 'bootstrap4', 'bootstrapform', mathfilters, 'django_filters', 'sorl.thumbnail', # Apps 'presence', 'confirmed list', 'topper', 'app_users.apps.AppUsersConfig', ] INSTALLED_APPS = list (set (SHARED_APPS + TENANT_APPS)) AUTH_USER_MODEL = 'app_users.ModelCustomUser' PUBLIC_SCHEMA_URLCONF … -
Django use a widget as a radio selection option
I would like to have a radio choice of a list of integer values in a Django form, however in the last option would be an integer field whereby the user can select their own value. Is this possible using a class based Form, or would it be easier to modify the template? At the moment I have passed the kwargs to the form ready to output, but am having trouble creating the integer selection as an option. At the moment I have: radio_choice = forms.IntegerField(initial=1, min_value=1) test = None def __init__(self, *args, **kwargs): ... super(InitForm, self).__init__(*args, **kwargs) self.fields['test'] = forms.CharField(label='Test', widget=forms.RadioSelect(choices=[(1,1),(2, 2),(3, self.fields['radio_choice'])])) but am getting on the page: <django.forms.fields.IntegerField object at 0x109e8b2b0> instead of the object