Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
For loop of javascript working for constant length like 4,5 or 6 but not working for carts.length
I am following a tutorial, but this piece of javascript code is not working at all. I tried to debug it using alert but I found that the first alert i.e 'going'alert is working but second alert 'work' alert is not working. When Ia am replacing 'carts.length with an integer like 3,4 or 5 it is working correctly This is the javascript code: let carts = document.querySelectorAll('.update-cart'); alert("going") for (let i=0;i < carts.length ;i++){ alert("work") console.log("looping"); } Tjis is the html code related to this: {% for i in product %} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src='/media/{{i.image}}' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{i.product_name}}</h5> <p class="card-text">{{i.desc}}</p> <button data-product="pr{{i.id}}" data-actions="add" class="btn btn-primary add-btn update-cart">Add to Cart</button> </div> </div> </div> {% if forloop.counter|divisibleby:4 and forloop.counter > 0 and not forloop.last %} </div> Please tell me what I am doing wrong. I want to use localStorage in javascript. I am using Django as backend. Thanks in advance. -
How to Display Model data in Django Admin?
I have 3 tables in my database, one is variant and another is variantoption and skuoptio, and variantoption table is related to variant table and variantoption table is related to skuoption, it means that variantoption table has variant_id and skuoption table has variantoption_id. Now i want variantoption data in two dropdown in admin panel. Please have a look in the given screenshot...this is my variantoption table and here is my variant table and my last table from where i am displaying variantoptions in admin panel here is my model.py file code. class Variants(models.Model): name=models.CharField(max_length=285, default=None) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) def __str__(self): return self.name code for variantoption table with relation variant_id class VariantOptions(models.Model): variant=models.ForeignKey('Variants', related_name='var_option', on_delete=models.CASCADE, null=True, blank=True) name=models.CharField(max_length=285) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) def __str__(self): return self.name here id my skuoption table code, i am using this for diplay data in admin panel class SkuOption(models.Model): product = models.ForeignKey('Product', null=True, blank=True, on_delete=models.CASCADE) variant=models.ForeignKey('Variants', related_name='SkuOption.variant+', on_delete=models.CASCADE, null=True, blank=True) variantoption=models.ForeignKey('VariantOptions', related_name='sku_option', on_delete=models.CASCADE, null=True, blank=True) sku=models.CharField(max_length=285, null=True, blank=True) price=models.CharField(max_length=285, null=True, blank=True) qty=models.CharField(max_length=285, null=True, blank=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) def __str__(self): return self.sku here is my admin.py file code for display variantoption class SkuOptionAdmin(admin.TabularInline): fieldsets = [(None, { 'fields':['sku','price','qty','variantoption','variant']})] model = SkuOption Please check admin panel image here, I want variantoption table … -
How long can Django with PostgreSQL run?
With no changes of code and no server fails, how long can a website using Django & PosgreSQL run being used by its end users? -
django query filter objects?
I wanna filter objects by category = 'shirt'. as seen below : models.py ''' CATEGORY_CHOICES = ( ('S', 'Shirt'), ('SW', 'Sport wear'), ('OW', 'Outwear') ) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() ''' views.py ''' class ShirtsView(View): def get(self, request): shirts = Item.objects.filter() return render(request, "shirts.html", {"shirts":shirts}) ''' thanx in advance -
Django Heroku Psycopg2 error Pysocopg2 module not found
I've tried the solutions to the problem already asked in the forum. But I'm unable to work this around. $ pip install psycopg2 Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: psycopg2 in /home/muni/.local/lib/python3.7/site-packages (2.8.5) My pip list contains: pip list Package Version ---------------------------- ---------------------- appdirs 1.4.4 asgiref 3.2.10 certifi 2020.6.20 chardet 2.3.0 command-not-found 0.3 defer 1.0.6 distlib 0.3.1 Django 3.0.8 filelock 3.0.12 gunicorn 20.0.4 importlib-metadata 1.7.0 language-selector 0.1 lightdm-gtk-greeter-settings 1.2.1 lxml 3.5.0 pip 20.1.1 pipenv 2020.6.2 psycopg2 2.8.5 psycopg2-binary 2.8.5 pycups 1.9.73 pycurl 7.43.0 pygobject 3.20.0 python-apt 1.1.0b1+ubuntu0.16.4.9 python-debian 0.1.27 pytz 2020.1 requests 2.9.1 setuptools 49.2.0 six 1.15.0 sqlparse 0.3.1 ssh-import-id 5.5 system-service 0.3 ubuntu-drivers-common 0.0.0 ufw 0.35 urllib3 1.13.1 usb-creator 0.3.0 virtualenv 20.0.27 virtualenv-clone 0.5.4 wheel 0.29.0 xkit 0.0.0 zipp 3.1.0 My app works fine with heroku local and python manage.py runserver. But fails only on git push heroku master. My pip file is as follows: [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] requests = "*" gunicorn = "*" django = "*" [requires] python_version = "3.7" My requirements file is as : asgiref==3.2.10 certifi==2020.6.20 chardet==3.0.4 Django==3.0.8 idna==2.10 psycopg2==2.8.5 pytz==2020.1 requests==2.24.0 sqlparse==0.3.1 urllib3==1.25.9 Database config under setting.py is : … -
Django ORM : one column multi join
My Wish Query SELECT `ERP_Art_Match_Cust`.`serial_no`, `CSV100`.`homepage_userid` AS `cs10`, `ArtMber`.`UserName` AS `us10`, `tb_member`.`card_rcp_type` AS `tb10` FROM `ERP_Art_Match_Cust` LEFT OUTER JOIN `ArtMber` ON (`ERP_Art_Match_Cust`.`userno` = `ArtMber`.`UserNo`) LEFT OUTER JOIN `CSV100` ON (`ERP_Art_Match_Cust`.`cust_id` = `CSV100`.`cust_id`) LEFT OUTER JOIN `tb_member` ON (`ERP_Art_Match_Cust`.`cust_id` = `tb_member`.`userid`) i wish using ERP_Art_Match_Cust.cust_id join twice My django ORM class ErpArtMatchCust(models.Model): serial_no = models.CharField(primary_key=True, max_length=50) Artmber = models.ForeignKey( "CSTMR_ADMIN.Artmber", null=True, on_delete=models.CASCADE, db_column="userno" ) Customer = models.ForeignKey( "CSTMR_ADMIN.Customer", null=True, on_delete=models.CASCADE, db_column="cust_id", ) TbMember = models.ForeignKey( "CSTMR_ADMIN.TbMember", null=True, on_delete=models.CASCADE, db_column="cust_id" ) class Meta: managed = False db_table = "ERP_Art_Match_Cust" app_label = "CSTMR_ADMIN" def __str__(self): return self.cust_id Error CSTMR_ADMIN.ErpArtMatchCust: (models.E007) Field 'TbMember' has column name 'cust_id' that is used by another field. HINT: Specify a 'db_column' for the field. i know db_column is duplicated. but my wish query is using join twice cust_id somebody help me @_@ -
Getting TypeError: 'function' object is not subscriptable this error during API creation
def operator_logincheck_web(request, email=None): data = json.loads email = data['email'] email = email.lower() password = data['password'] if Operator.objects.filter(email = email).count() > 0: if Operator.objects.filter(email = email, password = password).count() > 0: loginobj = Operator.objects.get(email = email, password = password) send_data = {'status':"1", 'msg':"Login Successfull", 'user_id':str(loginobj.id)} else: send_data = {'status':"0", 'msg':"Incorrect Password"} else: send_data = {'status':"0", 'msg':"Incorrect Email"} return JsonResponse(send_data) But geting this error on terminal File "/home/sumit/Cricket/CricketApp/views.py", line 1443, in operator_logincheck_web email = data['email'] TypeError: 'function' object is not subscriptable -
Make Docker compose wait for PostGIS (PostgreS) in Django project
I need to write a shell script that will allow docker to wait for postgres database. I have a following shell script named wait-for-postgres.sh : #!/bin/sh # wait-for-postgres.sh set -e host="$1" shift cmd="$@" until PGPASSWORD=$POSTGRES_PASSWORD psql -h "$host" -U "postgres" -c '\q'; do >&2 echo "Postgres is unavailable - sleeping" sleep 1 done >&2 echo "Postgres is up - executing command" exec $cmd docker-compose.yml : version: '3' services: db: image: kartoza/postgis:12.0 environment: - POSTGRES_DB=amr_or - POSTGRES_USER=postgres - POSTGRES_PASSWORD=root ports: - "5432:5432" web: build: ./ command: bash -c " ./wait-for-postgres.sh && python manage.py makemigrations && python manage.py migrate && python manage.py collectstatic --noinput --i rest_framework && gunicorn orion-amr.wsgi:application --bind 0.0.0.0:8000 --workers=2" ports: - "8000:8000" env_file: - ./.env.dev depends_on: - db Dockerfile: FROM python:2.7 WORKDIR /orion-amr/ ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt ./requirements.txt RUN pip install -r requirements.txt RUN apt-get update RUN apt-get install -y binutils libproj-dev gdal-bin COPY wait-for-postgres.sh /wait-for-postgres.sh COPY . /orion-amr/ How to add my existing commands from docker-compose.yml (python manage.py ..., etc) to shell script? -
Django database problems after pushing to github for heroku to build
I built my Django website locally, and tested it all locally and everything was working fine so I decided to get it on Heroku. I set it up so that I push it to a github project, then Heroku builds it from there and deploys it to the site. The only problem I'm having is with the database. Here's the setup in my settings.py: DATABASES = {'default': dj_database_url.config(conn_max_age=600, ssl_require=True)} if DATABASES['default'] == {}: DATABASES['default'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } At the end of the file I have "django_heroku.settings(locals())". So before I push it to github I clear the migrations folder only because I've been having problems, then I add, commit, push, and do the migrate via "heroku run --app app_name python manage.py migrate" which then tells me to do makemigrations before migrate, but I've already done it. So I've no idea what I'm doing wrong. Thank you in advance for any help. -
Django Extending class based view dynamically
Is there a good way to dynamically choose which view I want to extend in my class based view in Django? Right now I have 2 views(update and view) as follows that I would like to collapse into 1: from django.views.generic import UpdateView, DetailView from guardian.mixins import PermissionRequiredMixin class MyUpdateView(PermissionRequiredMixin, UpdateView): model = MyModel permission_required = 'MyApp.change_mymodel' template_name = "MyApp/update.html" fields = ["name", "Type", "description"] class MyDetailView(PermissionRequiredMixin, DetailView): model = MyModel permission_required = 'MyApp.view_mymodel' template_name = "MyApp/view.html" What I would like to do is have 1 view, and 1 url, and when the view is accessed if the user has the change permission, it should use UpdateView, if they have the view permission use DetailView, and if they have neither display some kind of error. Is there a way to make that work? -
AttributeError: 'NoneType' object has no attribute 'split' - Error when saving users in ajax call
Views.py The following attempt to save both my student (which extends User model) and my user, gives a long series of errors. What is the best way around this? I assume this is happening because it's an ajax call. I have been able to user the .save() in other views without an issue. Django version is 2.1.15 @login_required def start_membership(request): if request.method == 'POST': try: ... student.membership_start = membership_start_dt student.membership_end = membership_end_dt student.save() user = User.objects.get(id=request.user.id) user.membership = True user.save() ... Traceback Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python36\Lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\user\AppData\Local\Programs\Python\Python36\Lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\user\AppData\Local\Programs\Python\Python36\Lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\user\AppData\Local\Programs\Python\Python36\Lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Users\user\AppData\Local\Programs\Python\Python36\Lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "C:\Users\user\AppData\Local\Programs\Python\Python36\Lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Users\user\AppData\Local\Programs\Python\Python36\Lib\socketserver.py", line 803, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine [21/Jul/2020 00:09:40] "POST /students/start_membership/ HTTP/1.1" 500 59 Exception happened during processing of request from ('127.0.0.1', 60090) Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python36\Lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\user\AppData\Local\Programs\Python\Python36\Lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\user\AppData\Local\Programs\Python\Python36\Lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\user\AppData\Local\Programs\Python\Python36\Lib\wsgiref\handlers.py", … -
Django change and track order status
I have a status field in my model with a default value in progress. Whenever a new order is created a default value of in-progress is given to the order. Now I have added a new function, when a customer enters the order id it displays the status of the order. I want to add new functionality to my function in which when the customer enters the order.id and clicks track the order status should automatically change to scheduled. What can I add in my views function to make that work? models.py class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30) address = models.CharField(max_length=100 status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") views.py def order_tracker(request): if request.method=="POST": orderId = request.POST.get('orderId', '') try: order=Order.objects.filter(pk=orderId) if len(order)>0: update = Order.objects.filter(pk=orderId) updates = [] for order in update: updates.append({'status' : order.status}) response = json.dumps(updates) return HttpResponse(response) else: return HttpResponse('{}') except Exception as e: return HttpResponse('{}') return render(request,"tracker.html") {% extends 'base.html' %} {% block content %} <div class="container"> <div class="col my-4"> <h2>Enter your Order Id and Email address to track your order</h2> <form method="post" … -
state transition error in django-fsm and resetting the current state to default
I have an Order model which has a field status which has choices -> NEW (default), PENDING(PDG), DISPATCHED(DSP), COMPLETED(CMP), CANCELLED(CLD) models.py class Order(Address, TimeStampedUUIDModel): status = FSMField( max_length=25, choices=constants.STATUS_CHOICES, default=constants.NEW, ) @transition(field=status, source=constants.NEW, target=constants.PDG) def to_pending(self): self.status = constants.PDG @transition(field=status, source=constants.PDG, target=constants.DSP) def to_dispatched(self): self.status = constants.DSP @transition(field=status, source=constants.DSP, target=constants.CMP) def to_completed(self): self.status = constants.CMP @transition( field=status, source=[constants.NEW, constants.PDG, constants.DSP], target=constants.CLD, ) def to_cancel(self): self.status = constants.CLD serializers.py class OrderSerializer(serializers.ModelSerializer): class Meta: model = models.Order fields = "__all__" read_only_fields = [--all fields except status--] def update(self, instance, validated_data): status = validated_data.pop("status", None) agent = self.context['request'].user instance = services.status_function(status, instance, agent) return instance In the below services file I'm simultaneously trying to create an order activity object to track changes in Order object. services.py def status_function(status, instance, agent): if status is not None: switcher = { constants.PDG : instance.to_pending, constants.DSP : instance.to_dispatched, constants.CMP : instance.to_completed, constants.CLD : instance.to_cancel } func = switcher.get(status, None) try: func() models.OrderActivity.objects.create( event_name=status, order = instance, event = f"Order {status}", agent = agent, time = instance.modified_at ) except TransitionNotAllowed : print("Exception Caught") raise exceptions.BadRequest([{"error": "Transition not allowed"}]) return instance constants.py from extended_choices import Choices ## Order Status NEW, NEW_ = "NEW", "NEW" PDG, PDG_ = "PDG", "PENDING" … -
MySQL user privileges for testing Django app
I am using MySQL with Django. Are my only choices for allowing testing the following? I don't want to keepdb. GRANT ALL ON *.* to '<user>'@'localhost' so that the user can create test databases, etc. Test on sqlite which is almost the same thing but isn't MySQL and important if I am testing for everything. Option 1 seems a little unsafe and Option 2 still leaves the door open for untested areas. Is there another option in terms of the privileges I can grant or ways to think about it? -
Unable to authenticate user with Django Rest Framework from certain subdomains
My current setup consists of the following: 1) React JS application (react.example.com:3000) 2) Flask server to serve backend API calls (backend.example.com:5000) 3) Authentication server using Django Rest Framework (auth.example.com) I have configured the authentication server to use session authentication with these settings: SESSION_COOKIE_DOMAIN = '.example.com' CORS_ALLOW_CREDENTIALS = True SECURE_SSL_REDIRECT = True SESSION_COOKIE_SAMESITE = None SESSION_COOKIE_SECURE = False CSRF_USE_SESSIONS = True I have also setup an endpoint at auth.example.com/check_auth in Django to check if a user is authenticated def authorization(request): if request.user.is_authenticated: return HttpResponse('User is Authenticated') else: return HttpResponse('Not Authenticated') When I send a GET request to the endpoint from my ReactJS application after logging in, I receive the correct response 'User is Authenticated'. This works fine. However, I want send a similar request within certain endpoints in my Flask server but its not working. For example: @app.route('/check', methods=['GET']) def check_auth(): res = requests.get('https://auth.example.com/check_auth') return res.text After I login and send a GET request to backend.example.com:5000/check through the React application, I expected the return to be 'User is authenticated' but instead I get 'Not Authenticated'. This seems to imply that the django session cookie set to domain '.example.com' is not being sent to the Django authentication server? I'm confused as to … -
Django: display queryset in its corresponding ID (multiple ID)
My model is like this: class Hospital(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') hospital_name = models.CharField(max_length=1000) hospital_ategory = models.CharField(max_length=1000, choices=ETABLISSEMENTS) imagePopup = models.ImageField(upload_to='default/', default='default/musta.jpg') wilaya = models.CharField(max_length=200, choices=WILAYA) active = models.BooleanField(default=True) location = PointField(srid=4326) @property def lat_lng(self): return list(getattr(self.location, 'coords', []) [::-1]) def __str__(self): return self.hospital_name class Hospitalservice(models.Model): post = models.ForeignKey(Hospital, on_delete=models.CASCADE, related_name='services') name_service = models.CharField(max_length=10000, null=True, blank=True) responsable_service = models.CharField(max_length=10000, null=True, blank=True) service_date = models.DateTimeField(default=timezone.now) service_update = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) def __str__(self): return "{} à l'hopital {}".format(self.name_service, self.post.hospital_name) class Meta: ordering = ('-service_date', ) class Bedservice(models.Model): post_bed = models.ForeignKey(Hospitalservice, on_delete=models.CASCADE, related_name='bed') bed_number_total = models.IntegerField(null=True, blank=True) bed_number_used = models.IntegerField(null=True, blank=True) active = models.BooleanField(default=True) def __str__(self): return self.post_bed.name_service ` views.py looks like this: class HospitalTemplateView(TemplateView): template_name = 'health/hospital_map.html' queryset = Hospital.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["form"] = HospitalForm() ... ... ... return context def detail_imp_map(request, id): post = get_object_or_404(Hospital, id=id) services = post.services.filter(active=True) post_bed = get_object_or_404(Hospitalservice, pk=id) bed_service = post_bed.bed.filter(active=True) columns = ['bed_number_total'] num = reduce(add, (F(column) for column in columns )) Total_sum= Bedservice.objects.aggregate(total=Sum(num)) if request.method == "POST": service_form = HospitalServiceForm(request.POST, request.FILES) if service_form.is_valid(): new_point = service_form.save(commit=False) new_point.post = post new_point.save() return redirect('hospital_map') else: service_form = HospitalServiceForm() context={ 'post': post, 'post_bed': post_bed, 'Total_sum': Total_sum, 'services':services, 'service_form':service_form, } return render(request, … -
How to export text value instead of foreign key id from mysql table to excel in django
Good day everyone! I'am new to django and i want to learn a lot in this excellent framework. I want to learn in django-import-export application and I have trouble in exporting data from mysql table. Django-import-export application export foreign key id rather than the foreign key I specified in to_field. Below is my model from django.db import models class Rank(models.Model): RankCode = models.CharField(max_length=20, null=False, blank=False, unique=True) RankDesc = models.CharField(max_length=60, null=False, blank=False) OrderNo = models.IntegerField(null=True, blank=True) def __str__(self): return "%s" % self.RankCode class Status(models.Model): StatusCode = models.CharField(max_length=60, null=False, blank=False, unique=True) class Meta: verbose_name_plural = 'Status' def __str__(self): return "%s" % self.StatusCode class Student(models.Model): Rank = models.ForeignKey(Rank, to_field='RankCode', on_delete=models.CASCADE) Name = models.CharField(max_length=200, null=False, blank=False, unique=True) Status = models.ForeignKey(Status, to_field='StatusCode', on_delete=models.CASCADE) Age = models.IntegerField(null=True, blank=True) def __str__(self): return "%s" % self.Rank If I export Student model to excel, I want the output to be the value of specified foreign key in to_field and not the id. Thanks in advance to those who can contribute. -
I am running a Django test server on a remote Ubuntu nginx server. How can I access the Django interface from my local machine?
Right now, if I go to [remote server's IP] on Chrome, for example, it'll take me to the "Welcome to nginx" page. I have Django installed on this server, and when I run "python manage.py runserver" it starts the Django test server on which my app is stored. If this were on my local machine, I could just go to [localhost] on Chrome and it would show my Django app, but I'm not quite sure how to get to it on the remote server. Is this possible? Is there a better, cleaner way to do this - perhaps just configuring the Django project to run on the nginx server that is already created? -
Sending email via subdomain address with GSuite and Django
I've got G Suite/Gmail fully integrated with my django project and it works great. I'd like to send mail from a subdomain-based address, however (eg. support@mailer.mywebsite.com). I've gone into GSuite and added a new domain (support@mailer.mywebsite.com) and vertified control of the domain. Within my django project, I've updated the sender email to reflect the new address. from_email = 'support@mailer.mywebsite.com' send_mail( subject, txt_message, from_email, to_email, html_message=html_message, fail_silently=False, auth_user=authorizeduser.user_name, auth_password=authorizeduser.gsuite_app_password ) Unfortunately, the mail being sent out still has support@mywebsite.com as the sender. Thanks! -
Change the ordering of a TextField constrained by choices in the Django admin site
I would like to change the ordering of my size column in the Django admin site. The size column is based on a model.TextField with a choices constraint. Something like this: from django.db import models size_choices = [ ('P', 'Preemie'), ('N', 'Newborn'), ('0-3M', '0-3M), ('...', ), ] class Clothes(models.Model): size = models.TextField(max_length=20,choices=size_choices) with the following admin model: from django_admin_multiple_choice_list_filter.list_filters import MultipleChoiceListFilter class SizeListFilter(MultipleChoiceListFilter): title = 'Size' parameter_name = 'size__in' def lookups(self, request, model_admin): return size_choices @admin.register(Clothes) class ClothesObject(admin.ModelAdmin): list_display = ('get_name', 'type', 'size', '_seasons', '_colors', '_genders') list_filter = (SizeListFilter,TypeListFilter, SeasonListFilter, GenderListFilter) <snip> Now, I've made the probably unfortunate decision of having the id (the first element of each tuple) being the same as the label. It seems that, by default, clicking on the Size column heading on the admin site orders by ID. Changing the IDs to some numerical value causes a migration, but does not map the old IDs to the new IDs (as expected). How can I provide a custom ordering for the size TextField in the Django admin site? Ideally I'd want the items to appear in the same order that they do in the size_choices list. -
Wire Logging request payload from django application
I have a django python framework. I am making service calls to an API on Django POST request. I would like to know the request payload sent to the service from wire logs. How do I enable that? any inputs on this is appreciated? -
How do I query a full (or partial) name built from two separate model CharFields (first_name and last_name) in Django?
I'm trying to query a users full name using but am having some trouble. When I query either 'John' OR 'Doe' I get the correct result, but when I query 'John Doe' I do not. While I know my query is explicitly structured that way (first_name OR last_name), my question is how do I combine the fields such that any of 'John Doe', 'John Do', 'Jon D', etc. would produce the correct result? Model: class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __str__(self): return f"{self.last_name.title()}, {self.first_name.title()}" View: def search_results(request): query = request.GET.get('q') person_list = Person.objects.filter( Q(first_name__icontains=query) | Q(last_name__icontains=query)) context = {'person_list': person_list} return render(request, 'myapp/search_results.html', context) -
How to use the i18n with class based views and forms in Django?
I'm using Django 3.0.8 and I created a UserProfile-model in order to add more fields to the default django.contrib.auth.models.User-model with a OneToOne relation. I would like to use the default class based views such as django.contrib.auth.views.LoginView, LogoutView, PasswordChangeView, PasswordResetView. The problem is that the labels, the helptext and the error messages of the forms are standard and in the language indicated by the settings.LANGUAGE_CODE value. I tried to make custom form classes from the default Django form classes such as AuthenticationForm, PasswordChangeForm, PasswordResetForm or UserCreationForm. In the UserCreationForm, I also tried to add the form fields of the UserProfile-model so that the user can fill his/her profile data during his/her registration. The problem is that I must override every label, every helptext and every error message of each form in order to use ugettext on it. I would like to know if I'm wasting my time because the class based views and forms already supports ugettext. And if not, if there is a way to easily override the default labels, helptexts and error messages of each form. Here is what I currently made: This is the models.py-file: from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from … -
Is a GeoDjango MultiPolygonField supposed to accept a Polygon geometry?
When I try to set a Polygon on a MultiPolygonField the following exception is raised: Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/mattrowbum/.virtualenvs/my_env/lib/python3.7/site-packages/django/contrib/gis/db/models/proxy.py", line 75, in __set__ instance.__class__.__name__, gtype, type(value))) TypeError: Cannot set Location SpatialProxy (MULTIPOLYGON) with value of type: <class 'django.contrib.gis.geos.polygon.Polygon'> That would be understandable, except that a note in the GeoDjango tutorial states: ...a GeoDjango MultiPolygonField will accept a Polygon geometry. I've had a look at the source of proxy.py, and it is checking whether the value (a Polygon) is an instance of the relevant geometry class (a MultiPolygon). I've tried doing this check manually which confirms that a Polygon does not inherit from MultiPolygon: >>> from django.contrib.gis.geos import MultiPolygon, Polygon >>> ext_coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)) >>> int_coords = ((0.4, 0.4), (0.4, 0.6), (0.6, 0.6), (0.6, 0.4), (0.4, 0.4)) >>> poly = Polygon(ext_coords, int_coords) >>> isinstance(poly, Polygon) True >>> isinstance(poly, MultiPolygon) False Is the note in the tutorial misleading or am I doing something wrong? -
Django only returning first value of for loop
I am running a for loop with a button that submits a url. The buttons are in a for loop and when I press one, it only returns the first url of the for loop. My input looks like this: <input type="submit" id="choice{{ forloop.counter }}" value="Save" class="btn btn-primary" /> <input type="hidden" id="choice{{ forloop.counter }}" name="url" value="{{ article.articledata.url }}"> and my view looks like this: url = (request.POST["url"]) No matter which submit I press, I get the same request.POST value. Please help.