Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
If condition on Django html Template
jobseqno=P567890 <td> {% if jobseqno|first:"P" %}** <a href="{{ url }}{{ jobseqno }}" target="_blank">{{ jobseqno}}</a>{% endif %} </td> The above attached code doesn't work please help me out!! -
DJANGO: Product matching query does not exist
Error message I don’t understand what’s the matter. I do everything exactly according to the courses, but knocks out an error: Request URL: http://127.0.0.1:8000/products/basket-add/12/ Django Version: 3.2.4 Exception Type: DoesNotExist Exception Value: Product matching query does not exist. Add object: def basket_add(request, product_id): current_page = request.META.get('HTTP_REFERER') product = Product.objects.get(id=product_id) baskets = Basket.objects.filter(user=request.user, product=product) if not baskets.exists(): Basket.objects.create(user=request.user, product=product, quantity=1) return HttpResponsePermanentRedirect(current_page) else: basket = baskets.first() basket.quantity += 1 basket.save() return HttpResponsePermanentRedirect(current_page) Delete: def basket_delete(request, id): basket = Basket.objects.get(id=id) basket.delete() return HttpResponsePermanentRedirect(request.META.get('HTTP_REFERER')) template: <a href="{% url 'products:basket_delete' basket.id %}" style="text-decoration: none; color: gray;"> <i class="far fa-trash-alt"></i> </a> URLs: from django.urls import path from products.views import products, basket_add, basket_delete app_name = 'products' urlpatterns = [ path('', products, name="index"), path('basket-add/<int:product_id>/', basket_add, name="basket_add"), path('basket-add/<int:id>/', basket_delete, name="basket_delete"), ] Models: from django.db import models from users.models import User class ProductCategory(models.Model): name = models.CharField(max_length=64, unique=True) description = models.TextField(blank=True) class Meta: verbose_name_plural = "Product Categories" def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=256) image = models.ImageField(upload_to='products_images', blank=True) description = models.TextField(blank=True) short_description = models.CharField(max_length=64, blank=True) price = models.DecimalField(max_digits=8, decimal_places=2, default=0) quantity = models.PositiveIntegerField(default=0) category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE) def __str__(self): return f"{self.name} ({self.category.name})" class Basket(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=0) created_timestamp = models.DateTimeField(auto_now_add=True) … -
Bookmarking function django/python
I'm looking to create a model for users to bookmark a recipe. I have the below: models.py class RecipeBookmark(models.Model): recipe = models.ForeignKey( Recipe, on_delete=models.PROTECT, related_name="bookmarks" ) bookmarked_by = models.ForeignKey(User, on_delete=models.PROTECT) bookmarked_at = models.DateTimeField(auto_now_add=True) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ["username", "email", "date_joined"] class RecipeBookmarkSerializer(serializers.ModelSerializer): bookmarked_by = UserSerializer(read_only=True) class Meta: model = models.RecipeBookmark fields = ["recipe", "bookmarked_by", "bookmarked_at"] def create(self, validated_data): request = self.context["request"] ModelClass = self.Meta.model instance = ModelClass.objects.create( **validated_data, **{"bookmarked_by": request.user} ) return instance views.py @permission_classes([IsAuthenticated]) class RecipeBookmarkView(generics.CreateAPIView): queryset = models.RecipeBookmark.objects.all() serializer_class = RecipeBookmarkSerializer urls.py path("recipes/bookmarks/", PublishedRecipeBookmarkView.as_view()), I want to perform a lookup, given the recipe id through a POST request, to add the user to the bookmarks field, if the user already exists in the bookmarks field, to remove that user form the field (remove the bookmark). Many users can bookmark a given recipe. Also, How can a lookup be performed to return recipes that a logged in user has bookmarked via an api endpoint? -
Checkbox inside the "for" (loop), Django
my checkbox html : <form method="GET"> {% for subcategory in subcategories %} <div class="filter-items filter-items-count"> <div class="filter-item"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" value="{{subcategory.id}}" name="subcategory" id="{{subcategory.id}}" {% if subcategory in subcategories1 %} checked {% endif %}> <label class="custom-control-label" for="{{subcategory.id}}">{{subcategory}}</label> </div><!-- End .custom-checkbox --> <span class="item-count">{{subcategory.products.all|length}}</span> </div><!-- End .filter-item --> </div><!-- End .filter-items --> {% endfor %} <button type="submit" class="btn btn-primary w-100 mt-3">Filter!</button> </form> it work correctly to make filter. views : subcatid = request.GET.getlist('subcategory') query string: ?subcategory=5&subcategory=6 it can be one or more than one, depends on number of subcategories. but when I go next page i suppose it become like : ?page=2&subcategory=5&subcategory=6 but it remove earliest subcategory i choose and keep the last one, just one, like : ?page=2&subcategory=5 acutely when i put Manually ?page=2&subcategory=5&subcategory=6 in url field it works but not from pagination buttons. so while all checkboxes in filter has same names, name="subcategory" i made them unique by changing to name="{{subcategory}}", now each checkbox has unique name, now after tapping next page, Everything is kept, and there is no problem like before, but in views, I don't know how to get them with deafferents names subcatid = request.GET.getlist('subcategory') -
Post Multiple values as foreign key -- Django restframework
I have a model(ProfessionalMemberContacts) which has a primary key in different model(MasterProfessionalMembers). ProfessionalMemberContacts expects multiple or single set of details as per user input ie user could give multiple contact details. Problem: I cant figure out the way to loop over all the contact details(if multiple) to save in "ProfessionalMemberContacts" with reference to "MasterProfessionalMembers". Here is my models and views for it. Models.py class ProfessionalMemberContacts(models.Model): professionalmemberId = models.ForeignKey(MasterProfessionalMembers, default=None,on_delete=models.CASCADE, related_name="pro_contact") contact_person = models.CharField(max_length=100) contact_email = models.EmailField(max_length=100) contact_number = models.CharField(max_length=100) class MasterProfessionalMembers(models.Model): professionalmemberId = models.CharField(primary_key=True, max_length=100, default=1) profile_pic = models.ImageField(blank=True) organization_name = models.CharField(max_length=100) incorp_date = models.DateField(default=date.today()) organization_type = models.CharField(max_length=100) views.py def create_pro_individual_member(request): if request.method == "POST": contact_person = request.POST.get('contact_person') contact_email = request.POST.get('contact_email') contact_number = request.POST.get('contact_number') professionalmemberId =request.POST.get('professionalmemberId') member_object = MasterProfessionalMembers.objects.get(professionalmemberId=professionalmemberId) if len(contact_person) != 0: for p,ce,n in contact_person, contact_number, contact_email: reference = ProfessionalMemberContacts( contact_person = p, contact_email = ce, contact_number = n, professionalmemberId = member_object ) reference.save() return HttpResponse('professionalmember Id created as: '+professionalmemberId) Please suggest any way to save contact details provided by user. -
Failed to deploy Heroku app. ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize;
These are errors I am getting, I can't post the entire log because of the character limit sorry. Building wheel for psycopg2 (setup.py): started Building wheel for psycopg2 (setup.py): finished with status 'error' ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-mxd65ubh/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-mxd65ubh/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-mfz2er96 cwd: /tmp/pip-install-mxd65ubh/psycopg2/ Second Error: psycopg/psycopgmodule.c: In function ‘psyco_is_main_interp’: psycopg/psycopgmodule.c:689:18: error: dereferencing pointer to incomplete type ‘PyInterpreterState’ {aka ‘struct _is’} 689 | while (interp->next) | ^~ error: command '/usr/bin/gcc' failed with exit code 1 ---------------------------------------- ERROR: Failed building wheel for psycopg2 Running setup.py clean for psycopg2 Successfully built Pillow Failed to build psycopg2 Installing collected packages: docutils, jmespath, six, python-dateutil, urllib3, botocore, s3transfer, boto3, certifi, chardet, dj-database-url, pytz, Django, django-crispy-forms, whitenoise, psycopg2, django-heroku, django-storages, gunicorn, idna, Pillow, requests Running setup.py install for psycopg2: started Running setup.py install for psycopg2: finished with status 'error' Third Error: ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-mxd65ubh/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-mxd65ubh/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-08ru_8_3/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.9/psycopg2 cwd: /tmp/pip-install-mxd65ubh/psycopg2/ psycopg/psycopgmodule.c: In function ‘psyco_is_main_interp’: psycopg/psycopgmodule.c:689:18: error: dereferencing pointer to incomplete type … -
'QuerySet' object has no attribute 'approved'
I want to fetch all items from database where city=city_name and wnat to add one condition the area is approved or not but i am getting error about django query this is my code def parkingAreas(request, city_name): city_obj = City.objects.filter(city_name = city_name).first() reg_par = Registerparking.objects.all().filter(parking_city = city_obj) if reg_par.approved: param = {'par': reg_par} print(param) else: messages.error(request, 'Parking Not Found in Your Area') return render(request, 'parkingAreas.html', param) -
Django count function is not working and numbers aren't showing up
in the code i've written the boxes for completed and so on appear however the numbers/ the count function isn't working and the amount of each media isn't showing up pls help views.py from django.shortcuts import render from django.http import HttpResponse from .models import * # Create your views here. def home(request): media_continue_watching = Media.objects.filter(status="Continue Watching") media_plan_to_watch = Media.objects.filter(status="Plan to Watch") media_completed = Media.objects.filter(status="Completed") media_dropped = Media.objects.filter(status="Dropped") total_continue_watching = Media.objects.filter(status="Continue Watching").count() total_plan_to_watch = Media.objects.filter(status="Plan to Watch").count() total_completed = Media.objects.filter(status="Completed").count() total_dropped = Media.objects.filter(status="Dropped").count() context = {'media_continue_watching': media_continue_watching, 'media_plan_to_watch' : media_plan_to_watch , 'media_completed' : media_completed, 'media_dropped': media_dropped, 'total_continue_watching' : total_continue_watching, 'total_plan_to_watch' : total_plan_to_watch, 'total_completed' : total_completed, 'total_dropped' : total_dropped} return render(request, 'accounts/dashboard.html', context) def products(request): return render(request, 'accounts/products.html') def customer(request): return render(request, 'accounts/customer.html') models.py from django.db import models class Media(models.Model): CATEGORY = ( ('Movie', 'Movie'), ('Tv Show', 'Tv Show'), ('Drama', 'Drama'), ('Other', 'Other'), ) NUMBER = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ) GROUP = ( ('Action', 'Action'), ('Anime', 'Anime'), ('Comedy', 'Comedy'), ('Crime', 'Crime'), ('Fantasy', 'Fantasy'), ('Horror', 'Horror'), ('Romance', 'Romance'), ('Other', 'Other'), ) POSITION = ( ('Completed', 'Completed'), ('Continue Watching', 'Continue Watching'), ('Plan to Watch', 'Plan to Watch'), ('Dropped', 'Dropped'), ) title = models.CharField(max_length=200, null=True) language = … -
Django shows None type
My index.html file: views.py file: Terminal: -
Gunicorn returns "TypeError: expected str, bytes or os.PathLike object, not list" when testing Django site in Ubuntu server
I am following this tutorial on DigitalOcean for the setup of a Django site. After initial setup and migrations, when I test the usual python manage.py runserver 0.0.0.0:8000 it works well (showing all images and grabbing all static files) with no errors. When I test gunicorn --bind 0.0.0.0:8000 myproject.wsgi, no static files are grabbed (anyway, I understand that's Nginx's job) but this error appears for every static file requested in the page: Internal Server Error: /static/img/logo.png Traceback (most recent call last): (...) File "/usr/lib/python3.8/posixpath.py", line 76, in join a = os.fspath(a) TypeError: expected str, bytes or os.PathLike object, not list I suspect this is related to settings.py, where STATICFILES_DIRS are declared as a list, according to Django: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') This doesn't look to me related to collectstatic (but it could be). Why is it that there is no error in the Django server and when Gunicorn is used suddenly the list of paths is a problem? -
distinct on large table takes too long time in django
I have a large dataset with over 1m records. It has a manytomany field that causes duplicate returns on filtering. models.py: class Type(models.Model): name = models.CharField(max_length=100, db_index=True) class Catalogue(models.Model): link = models.TextField(null=False) image = models.TextField(null=True) title = models.CharField(max_length=100, null=True) city = models.CharField(db_index=True,max_length=100, null=True) district = models.CharField(db_index=True,max_length=100, null=True) type = models.ManyToManyField(Type, db_index=True) datetime = models.CharField(db_index=True, max_length=100, null=True) views.py: last2week_q = Q(datetime__gte=last2week) type_q = Q(type__in=intersections) city_district_q = (Q(*[Q(city__contains=x) for x in city_district], _connector=Q.OR) | Q(*[Q(district__contains=x) for x in city_district], _connector=Q.OR)) models.Catalogue.objects.filter(last2week_q & type_q & city_district_q).order_by('-datetime') distinct() is too slow and I'm looking for a different solution to remove duplicates. P.S: I also tried to use this query instead of type_q, but it's slower than distinct! because type_ids is a very large list. typ_ids = models.Catalogue.objects.only('type').filter(type__in=intersections).values_list('id', flat=True) type_q = Q(id__in=typ_ids) -
Trying to setup saleor in my windows machine and got this error while migrating
django.db.utils.OperationalError: FATAL: password authentication failed for user "qzwonwokfexnwy" FATAL: no pg_hba.conf entry for host "27.34.68.106", user "qzwonwokfexnwy", database "dclbs5vnp1cclj", SSL off DATABASES = { "default": dj_database_url.config( default="postgres://saleor:saleor@localhost:5432/saleor", conn_max_age=600 ) } -
Change Facebook login language in Django Allauth
I am using django-allauth to login users using Facebook. I want the authentication page in Facebook to show up in English and not the local language. I have tried changing the LOCALE_FUNC setting to lambda request: 'en_US' but it does not seem to cause any effect. Can anyone please show me where am I making the mistake. The full code is 'facebook': { 'METHOD': 'oauth2', 'SDK_URL': '//connect.facebook.net/{locale}/sdk.js', 'SCOPE': ['email', 'public_profile'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'INIT_PARAMS': {'cookie': True}, 'FIELDS': [ 'id', 'first_name', 'last_name', 'middle_name', 'name', 'name_format', 'picture', 'short_name' ], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'en_US', 'VERIFIED_EMAIL': False, 'VERSION': 'v7.0', }, One thing I noticed is that the LOCALE_FUNC is tied with SDK_URL and the method I have is oauth2. Is that causing the problem? -
how to serialize django models without rest framework?
I have 2 models. Let's assume each item can be sold only once. class Item(models.Model): name = models.CharField(max_length=150) price = models.FloatField() class ItemSold(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) purchased_on = models.DateTimeField(default=timezone.now) Now if I use django serializers.serialize I am getting only Item while I want both ItemSold and Item to be serialized, is there any way to do this simple thing without using django rest framework. I am trying to learn django and how this work now, so I would appreciate if you can show me django approach to do this. Thank you. -
I got this error: TemplateDoesNotExist at /tasks/ in Django
Environment: Request Method: GET Request URL: http://127.0.0.1:8000/tasks/ Django Version: 3.2.5 Python Version: 3.8.5 Installed Applications: ['hello', 'newyear', 'tasks', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.filesystem.Loader: C:\Users\Enclave\Django_For_Web\templates\tasks\index.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\Enclave\Django_For_Web\hello\templates\tasks\index.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\Enclave\Django_For_Web\newyear\templates\tasks\index.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\Enclave\AppData\Local\Programs\PythonCodingPack\lib\site-packages\django\contrib\admin\templates\tasks\index.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\Enclave\AppData\Local\Programs\PythonCodingPack\lib\site-packages\django\contrib\auth\templates\tasks\index.html (Source does not exist) Traceback (most recent call last): File "C:\Users\Enclave\AppData\Local\Programs\PythonCodingPack\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Enclave\AppData\Local\Programs\PythonCodingPack\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Enclave\Django_For_Web\tasks\views.py", line 7, in index return render(request, "tasks/index.html", { File "C:\Users\Enclave\AppData\Local\Programs\PythonCodingPack\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Enclave\AppData\Local\Programs\PythonCodingPack\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Users\Enclave\AppData\Local\Programs\PythonCodingPack\lib\site-packages\django\template\loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) Exception Type: TemplateDoesNotExist at /tasks/ Exception Value: tasks/index.html -
Write NestedStackedInline to Template
I wanted to pass all the information for one item added from NestedStackedInline admin (item specification) to template. Currently, it only passes one part of the information repeatedly from same category, instead of per category (like in image below). I have tried many times and still unsuccessful. Anyone can help? Image partial of the information Look of the nested of nested stacked inline in admin Template.html <div> {% for text in items %} <div> ...</div> {% endfor %} </div> <div class="text-left mt-4"> {% for title in specification %} <h4>{{title.group_title}}</h4> <table class="mb-5 mt-4 table"> <tbody> {% for detail in specification_detail %} <tr> <td scope="row" class="w-25">{{detail.specification_name}}</td> <td>{{detail.specification_definition}}</td> </tr> {% endfor %} </tbody> </table> {% endfor %} </div> Views.py def storeDetail(request, name): items = StoreItem.objects.filter(name=name) specification = itemSpecificationTitle.objects.filter(extra_key=items[:1]) specification_detail = itemSpecification.objects.filter(extra_key=specification) context={'items': items,'specification': specification, 'specification_detail': specification_detail,} return render(request, 'store-detail.html', context) Models.py class StoreItem(models.Model): name = models.CharField(max_length=200, blank=False) def __unicode__(self): return self.name class itemSpecificationTitle(models.Model): group_title = models.CharField(max_length=50, verbose_name="Category", blank=True) extra_key = models.ForeignKey(StoreItem) def __unicode__(self): return self.group_title class itemSpecification(models.Model): specification = models.CharField(max_length=500, verbose_name="Define specification", blank=True, help_text="One sentence. '=' to separate text (Size= 20X29X39 cm)") extra_key = models.ForeignKey(itemSpecificationTitle) def __unicode__(self): return self.specification def specification_name(self): return self.specification.split('=')[0] def specification_definition(self): return self.specification.split('=')[1][:] Admin.py class itemImages(NestedStackedInline): model = itemImages … -
How do i convert a descriptor field to an editable choicefield in django Admin
I have a @descriptor field in my django models called status. how do i make that field (status) editable and appear as a dropdown(choice field) of options in django admin -
Django password not hashed when creating new accounts
I'm new to django and am trying to discover why creating new accounts via my account form do not hash the password (I assume the passwords are not hashed because I cannot log in using the password when the account is created, and this message shows under the password field in the django admin for accounts created via the form: Invalid password format or unknown hashing algorithm). I can successfully create new accounts in the django admin that do not have this un-hashed password issue. views.py: @unauthenticated_user def create_account(request): form = AccountForm() if request.method == 'POST': form = AccountForm(request.POST) # should hash the password, check username/email doesnt already exist, etc if form.is_valid(): user = form.save() return redirect('/login') else: messages.info(request, "Count not create account.") context = {'form': form} return render(request, 'accounts/create_account.html', context) models.py: class Account(AbstractUser): def __str__(self) -> str: return self.first_name pass Create account form: <form action="{% url 'create_account' %}" method="POST"> {% csrf_token %} {{form.as_p}} <input type="submit" name="submit"> </form> The form: class AccountForm(ModelForm): class Meta: model = Account # which model we're building a form for # password not hashed and requires username even if username omitted from fields fields = ['email', 'password', 'first_name', 'last_name', 'username'] I'm following a tutorial series … -
AssertionError: 401 != 200
I am trying to write a test case for a bug report and I keep getting the assertion error. list_url = ('/bugreport') def setUp(self): self.owner = User.objects.create_user(username="asdf122223", password = "asdf1222345") self.token = Token.objects.create(user=self.owner) self.owner.save() self.api_authentication() def api_authentication(self): self.client.credentials(HTTP_AUTHORIXATION='Token ' + self.token.key) def test_bug_report_authenticate(self): response = self.client.get(self.list_url, format="json") self.assertEqual(response.status_code, status.HTTP_200_OK) def test_bug_report_un_authenticate(self): self.client.force_authenticate(user=None) response = self.client.get(self.list_url) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) if anyone can tell me what im doign wrong, that would be huge, or point me in the right direction -
Django Admin: How to select Groups roles to display based on active user role?
I have a Django app with multiple levels of admin role and users defined by the django-role-permissions package. I want to apply permissions to users only through groups, defining the permissions for the group roles and assigning the user to the correct group. I want to "hide" the higher level admin roles in Groups when lower level admins create users. A lower level admin should not be able assign a created user to a higher level admin role in Groups. I can do this with Users (lower level admins cannot view / change higher level admins) by overriding get_queryset with code shown below. I want to be able to do something equivalent with the roles in Groups. I would prefer to do this in my admin.py rather than in templates. It would have been nice if the Groups members were also gathered by get_queryset, but that does not seem to be the case. I have searched around without finding anything definitive. I set up django-debug-toolbar to see the context passed into the forms, but I don't see the Groups elements passed in that way to change_form. It's tempting to try overriding FilteredSelectMultiple inside of django.contrib.admin.widgets, but I don't yet see … -
Make Django admin work on a specific port
How to make Django administration URL work on a specific port? I am looking to run it on a unique port and then restrict the access to that port from the AWS security group to my IP. -
How to limit display data based on record value using Django Rest Framework?
I want to limit display data based on record data value. This is my code : models.py class Subcategory(models.Model): subcategory_id = models.BigAutoField(primary_key=True) subcategory = models.CharField(max_length=40) class Question(models.Model): question_id = models.BigAutoField(primary_key=True) subcategory = models.ForeignKey('Subcategory', models.DO_NOTHING, default=None) practice_setting = models.ForeignKey('PracticeSetting', models.DO_NOTHING, default=None) question = models.TextField() answer = models.CharField(max_length=255) class PracticeSetting(models.Model): practice_setting_id = models.BigAutoField(primary_key=True) num_of_question = models.SmallIntegerField() serializers.py class SubcategorySerializer(serializers.ModelSerializer): class Meta: model = Subcategory fields = ('subcategory_id', 'subcategory') class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ('question_id', 'subcategory', 'practice_setting', 'question', 'answer') class PracticeSettingSerializer(serializers.ModelSerializer): class Meta: model = PracticeSetting fields = ('practice_setting_id', 'num_of_question') view.py @api_view(['GET']) def subcategory_list(request): # GET list of subcategory if request.method == 'GET': subcategories = Subcategory.objects.all() subcategory = request.GET.get('subcategory', None) if subcategory is not None: subcategories = subcategories.filter(subcategory__icontains=subcategory) subcategories_serializer = SubcategorySerializer(subcategories, many=True) return JsonResponse(subcategories_serializer.data, safe=False) @api_view(['GET']) def question_list(request): # GET list of question if request.method == 'GET': questions = Question.objects.all() subcategory = request.GET.get('subcategory', None) if subcategory is not None: questions = questions.filter(subcategory__subcategory__icontains=subcategory) questions_serializer = QuestionSerializer(questions, many=True) return JsonResponse(questions_serializer.data, safe=False) @api_view(['GET']) def practiceSetting_list(request): # GET list of practiceSetting if request.method == 'GET': practiceSettings = PracticeSetting.objects.all() practiceSetting = request.GET.get('practiceSetting', None) if practiceSetting is not None: practiceSettings = practiceSettings.filter(practiceSetting__icontains=practiceSetting) practiceSettings_serializer = PracticeSettingSerializer(practiceSettings, many=True) return JsonResponse(practiceSettings_serializer.data, safe=False) /api/subcategory [ { subcategory_id: 1, subcategory: … -
Django AWS S3 Buckets: CKEditor gives SignatureDoesNotMatch error
I have put all of my static files in an S3 bucket on AWS. The images, javascript and CSS works fine on the site but the CKEditor rich text editor won't show up and is giving me the following errors: SignatureDoesNotMatch. The request signature we calculated does not match the signature you provided. Check your key and signing method TypeError: c[a] is undefined // I think that this error is only because of the first one There is also a script that didn't load in the console for the CKEditor which I think is also due to the signature error Here are my settings AWS_ACCESS_KEY_ID = id AWS_SECRET_ACCESS_KEY = secret_id AWS_STORAGE_BUCKET_NAME = bucket_name AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_REGION_NAME = 'eu-west-2' AWS_S3_ADDRESSING_STYLE = "virtual" TEXT_CKEDITOR_BASE_PATH = 'https://bucket_name.s3.amazonaws.com/ckeditor/ckeditor/' Note This error is happening also in the admin page so it's not the javascript that puts in the CKEditor that is causing the error so I haven't shared that javascript here as it is irrelevant -
Way to get custom queryset along with serialized relation response in django-rest-framework
Currently im implementing the django-rest-framework in my project. I want a custom response from my serializer (which is a serialized relation) but at the same time I also want to use custom queryset with query params so i implemented get_queryset()method in my generics.ListAPIView. Using this i cant get my custom serialized relations in my response. Serializer.py class ChainedSerializer(serializers.ModelSerializer): cate = serializers.SerializerMethodField() sub_cate = serializers.SerializerMethodField() class Meta: model = Chained exclude = ('id', 'shop') def get_cate(self, obj): cat = Cate.objects.get(id=obj.cate.id) print(cat) return cat.cate_name def get_sub_cate(self, obj): sub_cats = SubCate.objects.get(id=obj.sub_cate_id).sub_cate_name return sub_cats class ShopSerializer(serializers.ModelSerializer): shop = ChainedSerializer(read_only=True, many=True) class Meta: model = Shop fields = '__all__' Views.py class ShopList(generics.ListAPIView): queryset = Shop.objects.all() serializer_class = ShopSerializer permission_classes = (permissions.AllowAny,) def get_queryset(self): subcate = self.request.query_params.getlist('subcate') subcate_ids = list( SubCate.objects.filter(sub_cate_name__in=subcate).values_list('id', flat=True)) shop_ids = list(Chained.objects.filter(sub_cate_id__in=subcate_ids).values_list( 'shop_id', flat=True)) queryset = Shop.objects.filter(id__in=shop_ids).values() return queryset Response when using the ```get_queryset()``` method [ { "id": 1, "shop_type": "willodale", "shop_name": "first shop", "shop_email": "something@gmail.com", "phone": "1111111111", "area_code": "11111", "area_name": "dummy", "shop_address": "dummy", } ] Response if i dont use the get_queryset() method [ { "id": 2, "shop": [ { "cate": "Serv", "sub_cate": "WI" } ], "shop_type": "type", "shop_name": "dummy2", "shop_email": "something2@gmail.com", "phone": "1111111111", "area_code": "11111", "area_name": "dummy", "shop_address": "dummy", }, { … -
How do I validate input in Django REST framework before creation?
I have a model that represents a shopping item with a "choose-your-own-price" model. The seller can opt in to allow customers to pick from a low, medium, or high price. Thus, I need to validate that the user sends a valid option between these three values for each shopping item. Currently, my model looks like this: class PurchaseItem(models.Model): """ PurchaseItem. "price" should be treated as a suggestion. We allow users to choose their own price, so we need to validate that what comes here is a valid choice from the Listing. Otherwise, a malicious user might be able to charge whatever they want. The Listing model has a ListingPrice with a required 'suggested_cost' field and optional low, medium, high costs. """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) item = models.ForeignKey(Listing, on_delete=models.DO_NOTHING) price = models.DecimalField(max_digits=8, decimal_places=2, blank=False, null=False) currency = models.CharField(max_length=30, choices=SUPPORTED_CURRENCIES, default='USD') created_date = models.DateTimeField(auto_now_add=True) purchased_by = models.ForeignKey(User, on_delete=models.CASCADE) def clean(self): listing_price = self.item.price valid_prices = [listing_price.suggested_cost] if listing_price.supports_cost_choice is True: valid_prices = valid_prices + [listing_price.low_cost, listing_price.medium_cost, listing_price.high_cost] if self.price not in valid_prices: raise ValidationError("Selected price is not a valid option.") super(PurchaseItem, self).clean() def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.clean() # <---- Workaround. I'm trying to remove this. super(PurchaseItem, self).save(force_insert, force_update, …