Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, … -
Unable to read Django app files when hosting website through AWS using nginx and gunicorn
So I was trying to deploy a Django app through AWS using nginx and gunicorn. For some reason when I go to the ip it says "Welcome to nginx" and does not read my app files. This is the first time I am working with nginx and django, so does anyone have an idea what could be wrong? Is there any changes I need to make to my nginx.conf or django.conf or gunicorn.conf files? My wsgi.py file is in /Main/website/wsgi.py, unlike what you might usually find as /Main/wsgi.py This is my django.conf: listen 80; server_name ec2-18-191-164-253.us-east-2.compute.amazonaws.com; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/GMMR/app.sock; } } and this is my gunicorn.conf: directory=/home/ubuntu/GMMR/website command=/home/ubuntu/env/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/GMMR/app.sock website.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log [group:guni] programs:gunicorn this is my nginx.conf: worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## server_names_hash_bucket_size 128; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # … -
Django/Wagtail - How to create a conditional in template that checks for url path?
I'm struggling to finding a quick and easy solution to show HTML content based on a conditional that checks if the wagtail page is at root, aka '/'. According to the Wagtail docs, I can also make this work using original request object from Django: Additionally request. is available and contains Django’s request object. This is essentially what I want to do. I use the page object here from wagtail but it might be better if I used the request object from Django instead. How can I {% if page.request.path == '/' %} <div> show something </div> {% else %} #show nothing {% endif %} How can I structure a conditional to solve what I'm trying to do? -
Get a value from a JS script and pass it to a HTML Form
I don`t find out how to get the value from the js script input ( phone number that user input , and the country prefix code that the script auto put ) <script src="{% static 'assets/js/intlTelInput.js' %}"></script> <script> var input = document.querySelector("#phone"); window.intlTelInput(input, { initialCountry: "gb", }); </script> and have it saved thru my HTML form under this: <input type="tel" name="phone-number" class="form-control input-style" placeholder="your phone"> <input type="tel" id="phone"> Full code : <form class="submit-form" method="post" action="{% url 'register' %}" enctype="application/json"> {% csrf_token %} <div class="div-block"> <div class="double-fields-step-2-only"> <div class="form-group"> <div class="form-group right"> <input type="tel" name="phone-number" class="form-control input-style" placeholder="your phone"> <input type="tel" id="phone"> <script src="{% static 'assets/js/intlTelInput.js' %}"></script> <script> var input = document.querySelector("#phone"); window.intlTelInput(input, { initialCountry: "gb", }); </script> <div class="icon"></div> </div> </div> <button type="submit" class="btn btn-register" data-title="Loading..."> Register </button> </form></div> </form> -
Django: converting the "date_joined" field on the AbstractUser class to only month and year precision
I have a Django model with a User class that inherits from AbstractUser. class User(AbstractUser): pass In the Django Admin screen, I see that the date_joined field has month, day, year, and time precision. I also have a Django template with the following code: {% block header%} <h2>{{ profile.username }}</h2> <h3>{{ profile.date_joined }}</h3> {% endblock %} Not surprisingly, this renders as follows: Foo Bar July 4, 2021, 6:38 p.m. What I'd like is for it to render as only the month and date, as follows: Foo Bar July 2021 Is is possible to convert the date_joined field on the User class to month and year only? Thanks! -
Choosing a for loop based on if condition in Django
In Django How can I write condition for choosing one of two for loops? {% if type == 'type_one' %} {% for object in type_one_ojects %} {% elif type == 'type_two' %} # this_line {% for object in type_two_ojects %} ... ########## Given error ########## # Invalid block tag on this_line: 'elif', expected 'empty' or 'endfor'. Did you forget to register or load this tag? -
How do I save data to a table in Django?
I am trying to find the average price of each product and I am trying to store this in a table daily to form a price history chart, and all the objects will be data points on the chart. However, I am not able to create objects with the data I have, and I am not sure why. The Error I've gotten is <class 'OSError'> and I suspect it is because I am creating objects in the PriceHistory model incorrectly. class Command(BaseCommand): help = "Loops through each Retailer Product and scrapes their data" def handle(self,*args,**options): # Scrape Code happens here (cycles through all the retailerproduct objects, each object is recognised as 'product' in this script) # prices is just an array of all the prices for a particular product from several retailers mean = find_mean(prices,product) def find_mean(prices,product): mean = 0 for i in prices: mean += float(i) #This is where I am having problems: PriceHistory.objects.create(price=round(float(mean/len(prices)),2),product=int(product.product._id)) This is my PriceHistory Model class PriceHistory(models.Model): price = models.DecimalField(default=0.00,max_digits=8,decimal_places=2) product = models.ForeignKey(Product,on_delete=models.CASCADE,related_name='history') date = models.DateField(default=date.today,blank=True) _id = models.AutoField(primary_key=True,editable=False) This is my Product Model class Product(models.Model): name = models.CharField(max_length=30,null=True,blank=True) brand = models.CharField(max_length=20,null=True,blank=True) image = models.ImageField(null=True,blank=True) _id = models.AutoField(primary_key=True, editable=False) This is a table with all … -
django/react retrieve and play audio file
models.py from django.db import models from datetime import datetime class Song(models.Model): title = models.CharField(max_length=64) audio_file = models.FileField() genre = models.CharField(max_length=64) created_at = models.DateTimeField(default=datetime.utcnow) serializers.py from rest_framework import serializers from . import models class SongSerializer(serializers.ModelSerializer): class Meta: model = models.Song fields = '__all__' views.py from . import models, serializers from rest_framework import viewsets, status from rest_framework.response import Response from rest_framework.views import APIView class SongView(APIView): # get the songs def get(self, request, format=None): serializer = serializers.SongSerializer(models.Song.objects.all(), many=True) return Response(serializer.data) urls.py from django.urls import path from . import views urlpatterns = [ path('songs/', views.SongView.as_view(), name='songs') ] Home.js import React from 'react' import { useState, useEffect } from 'react' import axios from 'axios' const Home = () => { const getSongs = () => { axios.get('http://localhost:8000/api/songs/') .then(res => setSongs(res.data)) // see data below (Response.json) } let [songs, setSongs] = useState([]) useEffect(() => { getSongs() console.log(songs) }, []) return ( <> { songs.map(song => (<div className='music-controller'> <div className="music-controller-body"> <div className="music-controller-header"> <h2>{song.title}</h2> <p><small>{song.genre}</small></p> </div> <div className="controls"> <i className="fas fa-play"></i> <audio src={song.audio_file} autoPlay></audio> // Cannot retrieve url </div> </div> </div>) )} </> ) } export default Home Response.json [ { "id": 1, "title": "Kubbi | Cascade", "audio_file": "/media/Kubbi__Cascade.mp3", "genre": "Instrumental", "created_at": "2021-07-24T10:21:48Z" } ] All I want … -
How to show all fields values of a model from a form in Django?
I'm making a page to edit the user's account. The new values are saving with no problems, but I can't show the current values of the fields in the form (using forms.ModelForm). forms.py: class UserForm(forms.ModelForm): class Meta: model = User fields = ('email', 'first_name', 'last_name') class UsuarioForm(forms.ModelForm): class Meta: model = USUARIO fields = ('cpfCnpj', 'dataNascimento', 'telefone', 'receberNotificacoes', 'tipoUsuario' ) views.py: @login_required @transaction.atomic def modificar_cadastro(request): if request.method == "POST": user_form = UserForm(request.POST, instance=request.user) usuario_form = UsuarioForm(request.POST, instance=request.user.usuario) if usuario_form.is_valid() and user_form.is_valid(): user_form.save() usuario_form.save() return render(request, 'index.html') else: messages.error(request, ('Please correct the error below.')) else: usuario_form = UsuarioForm(instance=request.user) user_form = UserForm(instance=request.user.usuario) return render(request, 'modificar-cadastro.html', { 'usuario_form': usuario_form, 'user_form': user_form, }) template: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block conteudo %} <h2>Modificar cadastro</h2> <form method="POST" class="post-form">{% csrf_token %} {{ user_form|crispy }} {{ usuario_form|crispy }} <button type="submit" class="btn btn-outline-dark">Save</button> </form> {% endblock %} models.py: class USUARIO(models.Model): user = models.OneToOneField(User, on_delete=CASCADE) tipoUsuario = models.IntegerField(choices=TIPOS_USUARIO, default=1) cpfCnpj = models.CharField(max_length=11, blank=False, null=True, verbose_name='CPF') dataNascimento = models.DateField(blank=False, null=True, verbose_name='Data de nascimento') telefone = models.CharField(max_length=11, blank=True, null=True, verbose_name='Número de telefone') pontuacao = models.DecimalField(max_digits=30, decimal_places=15, blank=True, null=True) receberNotificacoes = models.BooleanField(default=False) What do i need to do to the current values to be displayed on my form? -
Django admin site downloading style-sheets but not displayed as styled
I have set up a basic Django system and am testing out the admin app. The admin screen displays with raw styles and not the pretty ones shown in the tutorials and specified in the style-sheets. Following several other questions, I found this is a common problem caused because Django doesn't normally serve static files. However, it does if DEBUG is switched on and I do have debug switched on. I followed all of the suggestions in the answers anyway to collect static files, etc. If I enter the static file URLs directly they get downloaded and I can see the files in the developer mode of the browser (both Chrome and Edge). So I think the static files are being served. Furthermore, if I save the page using the browser, it saves all of the static files and then if I open the main page it is shown with the correct styles. So the styles are working. So it would seem to me that the files are being served and the browser is getting them and it can render them (from a saved file) but it somehow isn't working when served from Django. Can anyone tell me what is … -
How i can show rows that have inputed value in new table?
This is my table : <table id="products"> <thead> <tr> <th>name</th> <th>quantity</th> </tr> </thead> {% for pr in productlist %} <tbody id="t1" class="tbody"> <tr class="test" data-index="pr.productid" style="border: none; border-collapse: collapse;"> <td> {{ pr.productname }} </td> <td> <input class="prqty" id="prinp" type="number" placeholder="0" max="pr.numberqut" min="0" name="mylist"> </td> </tr> </tbody> {% endfor %} </table> and this is result: Here i append to new table: <table id="here"></table> <script> $('#here').html($('#products').clone().attr('id', 'newproducts')); </script> My problem is that i don't know how can filters rows that have input value. i want this: Thanks for any help.