Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, how to save a randomly generated variable for the next session after POST method
I have an integer in Views.py which is generated randomly. I send it to Index.html: return render(request, 'index.html', {'number':number}) Then I have a simple form in forms.py class AForm(forms.Form): information = forms.CharField(label='Your answer', max_length=100) And this form in Index.html with POST method: <form action="{% url 'index' %}" method = POST> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> which leads to the same page and function. And I want to return via this POST method that number which I previously sent, because now it is already another, taken randomly, because it is the same function. But I already need the previous one. In other words I generate a random number and I need to save it for the next loading, after POST Method. I would even not send that number anywhere if it is possible. Is there a simple, elegant way to do it? I've read about sessions in Django, probably it is the way, but is there an easier way? Thanks. -
The concatenation returns me the name of the variable
I want to create an alert to delete users with sweetAlert, but in the script tag when I create my url from a variable passed as a parameter in the function, the result is only the name of the variable to display and not its value function delInscPart(id){ var url = "{% url 'suppPartners' " +id+" %}" Swal.fire({ "title":"Etes vous sure de vouloir supprimé l invité ?", "text":"Si vous confirmer cette opération, Vous supprimerais cette invité !", "icon":"", "showCancelButton":true, "cancelButtonText":"Anuller", "confirmButtonText":"Je confirme", "reverseButtons":true, }).then(function(result){ if(result.isConfirmed){ window.location.href = url console.log(url) } }) } <td><a href= "#" onClick="delInscPart('{{list.user_inscrit.username}}');"><i data-feather="trash-2"></i>Supprimer</a></td> the result is {% url 'suppPartners' +id+ %} instead {% url 'suppPartners' admin %} -
PyCharm: Cannot connect to postgres-db in docker container
as the title says, I'm having trouble to connect a rather simple database-configuration with my IDE PyCharm. docker-compose.yml db: restart: always image: postgres container_name: db volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=postgres ports: - "5432:5432" networks: - db-net Using it with django, here are my database-settings from the backend, which are working perfectly fine: settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": "postgres", "PASSWORD": "postgres", "HOST": "db", "PORT": 5432, } } But when trying to connect the database inside PyCharm with the following settings, I'm getting this error: Note: The field for password was of course filled -> get's cleared everytime someone hits Apply or tries to test the connection. Does anyone might know what I'm doing wrong or maybe had the same problem? Thanks for your help and have a great weekend! -
How Can I Check if Date is Passed from Django Model
I am really new in Django and I want to check if Date Stored in Model is passed. In fact, I am currently working on a ticketing app where users would have to purchase and activate ticket and I want to check if the Event Ticket Date is passed upon activation. My Models: class Event(models.Model): event_name = models.CharField(max_length=100) date = models.DateField(auto_now_add=False, auto_now=False, null=False) event_venue = models.CharField(max_length=200) event_logo = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images') added_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.event_name}" #Prepare the url path for the Model def get_absolute_url(self): return reverse("event_detail", args=[str(self.id)]) class Ticket(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) price = models.PositiveIntegerField() category = models.CharField(max_length=100, choices=PASS, default=None, blank=False, null=False) added_date = models.DateField(auto_now_add=True) def __str__(self): return f"{self.event} " #Prepare the url path for the Model def get_absolute_url(self): return reverse("ticket-detail", args=[str(self.id)]) def generate_pin(): return ''.join(str(randint(0, 9)) for _ in range(6)) class Pin(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) value = models.CharField(max_length=6, default=generate_pin, blank=True) added = models.DateTimeField(auto_now_add=True, blank=False) reference = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4) status = models.CharField(max_length=30, default='Not Activated') #Save Reference Number def save(self, *args, **kwargs): self.reference == str(uuid.uuid4()) super().save(*args, **kwargs) def __unicode__(self): return self.ticket class Meta: unique_together = ["ticket", "value"] def __str__(self): return f"{self.ticket}" def get_absolute_url(self): return reverse("pin-detail", args=[str(self.id)]) My Views for … -
How to loop websocket events in django in a roulette game
Hello fellow programmers, I'm currently using Django with WebSockets to create a replica close to https://bloxflip.com/roulette or any kind of online synchronized roulette you can have that involves multiple bets from all different players. I am at this stage attached image, and I'm trying to create a backend loop that will run between states (Waiting for bets, Calculating hashes, Rolling, Restarting), the only solution I got is using workers from Celery that will loop it on a Redis server. I wonder if there is any other solution that can help me make this loop in the backend so I can send it to the frontend with WebSockets. Let me know what other method i can use or if i can improve my actual code. consumers.py class RouletteConsumer(WebsocketConsumer): def connect(self): self.room_group_name = 'roulette' async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept()` current_state = states[0] self.send(text_data=json.dumps({ 'type':'current_state', 'current_state': current_state })) def receive(self, text_data): text_data_json = json.loads(text_data) bet_data = text_data_json['bet_data'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type':'send_bet', 'bet_data': bet_data, } ) def send_bet(self, event): bet_data = event['bet_data'] self.send(text_data=json.dumps({ 'type':'bet', 'bet_data': bet_data })) def current_state(self, event): state = event['current_state'] self.send(text_data=json.dumps({ 'type':'state', 'current_state': state })) -
How to store token from another api in Django?
In my DJango application I use another API external to my application. To authenticate on the external API, I must first make a POST with my credentials, and get a JWT token. Once this token is retrieved, I have to put it in the headers to be able to make requests on the api. Once the token is retrieved (thanks to requests), how to store it in a "global" way to be able to reuse it until it expires ? -
Store the primary key but display the name of an instance in Django Forms
I created a form through which the user can send an email to customers. I wanted to create a UI where the user can select a customer from the list of customers and automatically after clicking the customer, the email field is updated(i.e., the customer's email). I have done this before and the Foreign Key relation works the best but in this case, I think there is no need to create a different app for Email support and then give the foreign relations, etc. forms.py: class EmailForm(forms.Form): customer = forms.CharField(widget=forms.Select) email = forms.CharField(max_length=100) subject = forms.CharField(max_length=100) attach = forms.FileField() message = forms.CharField(widget = forms.Textarea) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['customer'].widget.choices = [(i.name, i.name) for i in Customer.objects.all()] email.html: {{ customer_data|json_script:"customerdata" }} <script type="text/javascript"> var customerdata = JSON.parse(document.getElementById('customerdata').textContent); document.getElementById('id_customer').onchange = function(event){ var cust = customerdata.find(({customer_id}) => customer_id == event.target.value); document.getElementById('id_email').value = cust && cust.email ? cust.email : ""; }; I am passing the Customer data to the email.html using JSON but I am not able to assign the email to the appropriate field because id_customer returns a String, i.e., The customer name and not the customer_id as I want. I understand that I am purposely displaying the customer_name instead of … -
Django.urls reversing urls through multiple url pattern lists within one app
I have a url.py inside my project which includes the following urls.py (belongs to my app). urls.py from django.urls import path,include from .views import Index, Foo bar_urlpatterns = [ path('foo/', Foo.as_view(), name='foo'), ] urlpatterns = [ path('', Index.as_view(), name='index'), path('bar/', include(bar_urlpatterns)),] I'm trying to outsource the subpaths of a path. The docs says the function include can include a pattern_list and when i call the url"http://myurl/foo/bar" directly, this seems to hold true. I can also load the view via ajax directly when i give it the string. But when i try to use the reverse {%url 'foo'} url template tag this throws: Uncaught SyntaxError: Invalid regular expression flags(at ...) Doing the same thing with non-outsourced url patterns works perfectly fine for me. The html elements where i use the function: <a onclick="load_tab_view({% url "foo" %})">Foo</a> <div id="tab_view_replaceable"></div> js (works fine with my other views) function load_tab_view(url){ replace_id = 'tab_view_replaceable'; $.ajax({ url: url, type: 'GET', dataType: 'html', success: function(data){ $('#'+replace_id).html(data); } }); } Is there a way in which im still able to outsource my subpaths and make use of the reverse url template tag? (I dont want to create a new app for bar) -
Celery scheduler not performing the task
I was trying to use Celery to query an external api at a regular frequency and update my database in my Django project with the new data. Celery schedules the task correctly and sends it to the celery worker but it never executes anything. Here is my celery.py file which is at the same level as my settings.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings from celery.schedules import crontab os.environ.setdefault("DJANGO_SETTINGS_MODULE", "data_analysis.settings") app = Celery("data_analysis") app.conf.enable_utc = False app.conf.update(timezone= 'Asia/Kolkata') app.config_from_object(settings, namespace="CELERY") app.autodiscover_tasks() app.conf.beat_schedule = { 'update_all_api':{ 'task':'operations.tasks.celery_update', 'schedule': 30.0, } } @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') This is my tasks.py which is inside an app named 'operations': from celery import shared_task import time from operations.models import Machine, MachineData from operations.analytics.processing import get_data @shared_task(bind=True) def celery_update(self): print('Running Update') print('The time is :' + str(time.asctime(time.localtime(time.time())))) print('Getting Data ...') all_machines = Machine.objects.all() for machine in all_machines: data_list = get_data(machine.api_url) for data in data_list: # print(data) if not MachineData.objects.filter(data=data): print('New Data received for :' + str(machine)) MachineData.objects.create(machine=machine, data=data) else: print('No new data for : ' + str(machine)) return 'done' The scheduler sends the task to the celery worker, but it never executes the function. Here is … -
HOW TO PULL ALL USERS FROM AD AND STORE THEM IN DATABASE BY USING DJANGO AUTH LDAP
I am Using Django 4.4, I have managed to authenticate users by using django-auth-ldap.But I can not get all users records to my database. I have tried to follow instructions from this link using the filter "sAMAccountType=805306368)", It gives all users and their groups but they cant be updated to django admin panel, Users are only displayed in the debug file only and users can not be binded to login here is how my configurations look like AUTH_LDAP_SERVER_URI = "mydomain.com" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_REFERRALS: 0 } AUTH_LDAP_BIND_DN = "user@mydomain" AUTH_LDAP_BIND_PASSWORD = "password" LDAP_IGNORE_CERT_ERRORS = True AUTH_LDAP_USER_SEARCH = LDAPSearch( "DC=mydomain,Dc=com", ldap.SCOPE_SUBTREE, "(sAMAccountType=805306368)" ) AUTH_LDAP_GROUP_TYPE = PosixGroupType(name_attr='cn') -
Webpack is compiling successfully but changes are not reflected in React App
I am using Django to host the react app which is being compiled by babel and bundled using webpack. The webpack shows me a compiled successfully message like below but the changes aren't reflected. The funny thing is when I wait for a bit, it works but that too sometimes with no linear pattern. I am getting mad about this, please help! I saw that, since I am using OSX, it is getting corrupted as the github issue says: https://github.com/webpack/webpack-dev-server/issues/24 but it is not helping! npm run dev > frontend@1.0.0 dev > webpack --mode development --watch asset main.js 1.32 MiB [compared for emit] [minimized] (name: main) 1 related asset runtime modules 1.04 KiB 5 modules modules by path ./node_modules/ 1.2 MiB modules by path ./node_modules/axios/ 56.8 KiB 32 modules modules by path ./node_modules/react-dom/ 1000 KiB 3 modules modules by path ./node_modules/react/ 85.7 KiB 2 modules modules by path ./node_modules/scheduler/ 17.3 KiB 2 modules + 5 modules modules by path ./src/ 36.6 KiB modules by path ./src/components/*.js 30.3 KiB ./src/components/App.js 1.58 KiB [built] [code generated] + 9 modules modules by path ./src/*.js 6.33 KiB ./src/index.js 35 bytes [built] [code generated] + 2 modules webpack 5.74.0 compiled successfully in 2567 ms assets … -
Django cannot save to to second database
i've tried using multiple database in my django projects, then i create a models with foreign key to User, it can't save to second database this is the UserData models class UserData(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user', related_query_name='user') is_controller = models.BooleanField(default=False) phone_number = models.CharField(max_length=255, blank=True, null=True) then in views instance = UserData( user=request.user, nim=nim, phone_number=phone ) after that, i save the instance >>> instance.save() #it works on default database (sqlite) >>> instance.save(using='db_alias') # return an error the error said it was cannot add or update child row because of the foreign key (1452, 'Cannot add or update a child row: a foreign key constraint fails (labs.presence_userdata, CONSTRAINT presence_userdata_user_id_4b3dfc56_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user (id))') can anyone help me solve this problem -
Django, create table or page just to join all other tables into one and show it. is it possible?
I want to show info from different tables together in another page or table. But I don't want create another table with duplicate info. Is it possible to Join many tables and show in some admin page? -
How to get value of a nested serializer field from its parent serializer class?
Consider the followings two serializers: class SerializerA(BaseSerializer): field_1 = serializers.IntegerField() field_2 = SerializerB() class SerializerB(BaseSerializer): field_3 = serializers.IntegerField() The input JSON for SerializerB will not contain field_3 and it has to obtained from field_1 of SerializerA. I have tried this class SerializerB(BaseSerializer): field_3 = serializers.IntegerField() def __init__(self, instance=None, data=empty, **kwargs): if data is not empty and isinstance(data, dict): _data = data.copy() _data['field_3'] = self.parent.initial_data.get('field_1') super(SerializerB, self).__init__(instance, _data, **kwargs) super(SerializerB, self).__init__(instance, data, **kwargs) But it is not working as data is always empty and it never passes the if statement. -
The admin isn't submitting data in django
I have written this code using django: in models.py(in the app): class Feature2(models.Model): name = models.CharField(max_length=100) detail = models.CharField(max_length=500) in URLs.py(in the app) urlpatterns = [ path('2', views.index, name='index2'), ] in admin.py(in the app): 'admin.site.register(Feature2)' in app's templates (index2.html): <div class="row icon-boxes"> {% for feature in xfeatures %} <div class="col-md-6 col-lg-3 d-flex align-items-stretch mb-5 mb-lg-0" data-aos="zoom-in" data-aos-delay="200"> <div class="icon-box"> <div class="icon"><i class="ri-stack-line"></i></div> <h4 class="title"><a href="">{{feature.name}}</a></h4> <p class="description">{{feature.details}}</p> </div> </div> {%endfor%} </div> </div> in views.py (in app): def index2 (request): xfeatures = Feature2.objects.all() return render(request,'myapp/index2.html', {'xfeatures': xfeatures}) in urls.py in project: urlpatterns = [ path('admin/', admin.site.urls), path('myapp/', include("myapp.urls")) ] when I run admin in the browser and enter data in features2 this appears to me: in this photo so what is wrong in my code? -
Django template filter remove image
My Problem I was making posts and postdetail page using summernotes. I using summetnote made 2 pictures and sentences I use truncatechars_html:100|safe I want to image remove in the post page I want to show photos uploaded to summernote only when I go to postdetail. post.html content code without using safe I just want the image to be invisible <div style="text-align: center;">Make post and two image</div> <div style="text-align: center;"><br></div><div style="text-align: center;">wdljawlkdjkawd</div> <div style="text-align: center;"><img src="/media/django-summernote/2022-08-06/31910af9-4366-48ad-aae1-8fc523d87181.jpg" style="width: 698.011px;"><br></div> <div style="text-align: center;"><img src="/media/django-summernote/2022-08-06/3c7f7804-a5d7-4cd3-b69b-bea66fd6b121.png" style="width: 698.011px;"><br></div> post.html <div class="container mt-5"> <div class="row"> <div class="col-lg-12"> <!-- Post content--> <article> <!-- Post header--> {% for post in Post_list %} <header class="mb-4"> <!-- Post title--> <h1 class="fw-bolder mb-1"><a href="{% url 'post_detail' post.id %}"> {{ post.title }}</a></h1> <!-- Post meta content--> <div class="text-muted fst-italic mb-2">{{ post.create_time }}</div> </header> <section class="mb-5"> <p class="fs-5 mb-4">{{ post.content|truncatechars_html:100|safe }}</p> </section> {% endfor %} </article> </div> </div> </div> post_detail.html <div class="container mt-5"> <div class="row"> <div class="col-lg-12"> <!-- Post content--> <article> <!-- Post header--> <header class="mb-4"> <!-- Post title--> <h1 class="fw-bolder mb-1"><a href=""> {{ post.title }}</a></h1> <!-- Post meta content--> <div class="text-muted fst-italic mb-2">{{ post.create_time }}</div> </header> <section class="mb-5"> <p class="fs-5 mb-4">{{ post.content|safe }}</p> </section> </article> </div> </div> </div> -
python manage.py migrate: ValueError: too many values to unpack (expected 2)
i just create django project and run python manage.py migrate and receive this error ValueError: too many values to unpack (expected 2) ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ python 3.10⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ django 4.1 -
Shoud I must delare global in python when i change list in function?
This is my code. my_list = [{"id": 1, "data": "Python"}, {"id": 2, "data": "Code"}, {"id": 3, "data": "Learn"}] def this(): for index in range(len(my_list)): if my_list[index]["id"] == 2: del my_list[index] break this() print(my_list) >>> [{'id': 1, 'data': 'Python'}, {'id': 3, 'data': 'Learn'}] I can see that my_list[1] has removed. But I have a problem. I don't declare global my_list , but why I can change a list outside of function in function? -
django.db.utils.IntegrityError: NOT NULL constraint failed: user.id
I don't know why the error is caused even though I designated the author. I'd appreciate your help. model & form class SuperTitle(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='debate_author') super_title = models.CharField(max_length=100) liker = models.ManyToManyField(User, related_name='debate_liker') def __str__(self): return self.super_title class SuptitForm(forms.ModelForm): class Meta: model = SuperTitle fields = ['super_title'] views.py def create(request): ... dic = {'super_title' : request.POST.get('sup_title')} sup_form = SuptitForm(dic) if sup_form.is_valid(): sup_form.author = request.user sup_form.super_title = ... sup_form.save() ... return IntegrityError at /polls/debate/create/ NOT NULL constraint failed: polls_supertitle.author_id -
How to apply lookups in django filter query according to conditions?
I want to make a query where i can apply lookups only when some conditions satisfy. e.g A customer can pick only that food from stall for which he paid for class Customer(models.Model): food_type = models.CharField() fruit_id = models.ForeignKey(Fruit, null=True) vegetable_id = models.ForeignKey(Vegetable, null=True) is_paid = models.BooleanField() class Food(models.Model): fruit_id = models.ForeignKey(Fruit, null=True) vegetable_id = models.ForeignKey(Vegetable, null=True) So i need to do something like: q = Food.objects.all() if Customer.objects.filter(id=(id of customer), food_type='fruit', is_paid=True).exists(): q = q.filter(fruit_id__in=Customer.objects.filter(id=(id of customer), food_type='fruit', is_paid=True).values_list('fruit_id', flat=True)) if Customer.objects.filter(id=(id of customer), food_type='vegetable', is_paid=True).exists(): q = q.filter(vegetable_id__in=Customer.objects.filter(id=(id of customer), food_type='vegetable', is_paid=True).values_list('vegetable_id', flat=True)) How can i optimize this as this is a small example, in my case there are many more conditions. I want to reduce the number of times it is hitting the database. Also is there any way i can use conditional expressions here? e.g When() Any help will be appreciated. -
ModuleNotFoundError: No module named 'html.entities'; 'html' is not a package
Newbie coder here. So im trying to pipenv install django but i keep getting this error : $ pipenv install django Creating a virtualenv for this project... Pipfile: C:\Users\wesleyromero308\Desktop\Pipfile Using C:/Users/wesleyromero308/AppData/Local/Programs/Python/Python38/python.exe (3.8.0) to create virtualenv... [= ] Creating virtual environment...ModuleNotFoundError: No module named 'html.entities'; 'html' is not a package Failed creating virtual environment [pipenv.exceptions.VirtualenvCreationException]: 2022-08-06 01:08:46.004 ERROR root: ModuleNotFoundError: No module named 'html.entities'; 'html' is not a package Failed to create virtual environment. I then went and did pip install htmlentities and it was successful. Then i did pip install html and got this error: $ pip install html Collecting html Using cached html-1.16.tar.gz (7.6 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error python setup.py egg_ifo did not run successfully. exit code: 1 [1 lines of output] ERROR: Can not execute `setup.py` since setuptools is not available in the build environment. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed Encountered error while generating package metadata. See above for output. Please help, i just want to install django lol i been stuck for days now -
Fail to enable Smartsheet webhook (502 Bad Gateway)
Django: 4.0.6 Smartsheet Python SDK: 2.105.1 Ngrok: 3.0.6 I have a Django server running on localhost, forwarded my localhost through Ngrok, have setup a callback route for accepting/responding to the Smartsheet-Hook-Challenge, and created a webhook instance using Python SDK. However, when I try to enable my webhook by running the following (documented here): Webhook = smartsheet_client.Webhooks.update_webhook(webhook_id,smartsheet_client.models.Webhook({'enabled': True})) Ngrok immediately returns 502 bad gateway, and my webhook instance's disabledDetails attribute becomes Request returned HTTP status code 502 (ref id: wtegm9). And I have no clue what's the cause of this 502. PS: While I'm writing this question, I was able to successfully enable my webhook using cURL command, so I can go ahead and start working. But enabling the same webhook instance with update_webhook python method still gives 502. Since updating webhook with cURL worked, could it be a bug in the Python SDK method itself? -
DRF - The serializer field might be named incorrectly and not match any attribute or key on the `str` instance
I'm trying to save my update serialize. The predict field is changed to the value predicted by Inference code(Image Classfication model). But I get the error: AttributeError at /predict/product/1/ Got AttributeError when attempting to get a value for field image on serializer ProductSerializer. The serializer field might be named incorrectly and not match any attribute or key on the str instance. Original exception text was: 'str' object has no attribute 'image'. AttributeError at /predict/product/1/ Got AttributeError when attempting to get a value for field image on serializer ProductSerializer. The serializer field might be named incorrectly and not match any attribute or key on the str instance. Original exception text was: 'str' object has no attribute 'image'. I checked migrations. Views.py from django.shortcuts import render from rest_framework.response import Response from .models import Product from rest_framework.views import APIView from .serializers import ProductSerializer from django.http import Http404 from rest_framework import status, viewsets #from .inference_code import predict from .apps import ProductConfig import json class ProductListAPI(viewsets.ViewSet): serializer_class = ProductSerializer queryset = Product.objects.all() def get(self, request): queryset = Product.objects.all() print(queryset) serializer = ProductSerializer(queryset, many=True) return Response(serializer.data) def post(self,requset): serializer= ProductSerializer( data=requset.data) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) class ProductPredictAPI(APIView): def get_object(self, pk): try: return Product.objects.get(pk=pk) except Product.DoesNotExist: raise Http404 def … -
Django pull list of all users, but shows list of multiple users with only current users credentials
In Django, I am trying to get a list of all users. I use the following query: users = User.objects.all().order_by('id') I am able to get a list of all the users, but it outputs a list of all users, but only showing the current users credentials? If I have 20 users, it will show 20 users but only the information for the currently logged in user. For example, I want to see a table like: User | Email ------------ User1 | user1@test.com User2 | user2@test.com User3 | user3@test.com But if the current user that is logged in is User1, It shows: User | Email ------------ User1 | user1@test.com User1 | user1@test.com User1 | user1@test.com Or if User2 is logged in, it shows: User | Email ------------ User2 | user2@test.com User2 | user2@test.com User2 | user2@test.com Here is my view.py: def portal_users(request): users = User.objects.all().order_by('id') return render(request, 'portal/users.html', {"users": users}) templates {% for users in users %} <tr> <td>{{user.username}}</td> <td>{{user.email}}</td> </tr> {% endfor %} -
Django.db.models.field.CharField
I have a Django project that I'm trying to cobble together for a very basic survey that needs to be entered for demographic information. I've dummied up some data through the admin site in order to get my ListView working for the time being. Unfortunately I'm getting a strange response. I built the models.py to be a drop down of a full spelled out and then to keep it small, I've made the actual storage in the db 1-3 characters. When I get my list view, one that uses 1 character to store for gender presents as (<django.db.models.fields.CharField>,), I would like for it to present as as the larger name of "Male", "Female", "Non-binary". However for my race and ethnicity fields which are 2 & 3 characters, those are returning as the actual storage for the DB (i.e, 'AA', 'NHP'). I'm more comfortable with SQL, so I'm not opposes to adding a table for a key as there would only be 11 entries for now, but its possible that more things could be added down the line. models.py: from django.db import models from django.contrib import admin from django.contrib.auth.models import User # Create your models here. class StuData(models.Model): id_num = models.IntegerField(primary_key=True) …