Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django execute save() on database [duplicate]
I've been doing some work in Django and noticed most people push save() right away after the change to model has been made for example in SQLAlchemy if we loop over few db objects and do modification after the loop we can say db.session.commit() saying to commit everything that has been done and save some performance but committing in bulk rather on each loop Is there a similar function for Django? -
why scheduled job using corn is not working in django?
I've used https://pypi.org/project/django-crontab/to tutorial to schedule corn job but it is not working: I added INSTALLED_APPS = [ ..., 'django_crontab', ] CRONJOBS = [ ('*/1 * * * *', 'allActivitiesApp.cron.sendNotification', '>> /path/to/log/file.log'), ] In allActivitiesApp -> corn.py: from .models import * def sendNotification(): # notificationList = dateBasedNotificaton.objects.filter(scheduleDate = date.today()) obj = test(name="working") obj.save() obj.refresh_from_db() # print("sending notifications/messages") return "success" but it is not doing anything when I tried to get logs I found: Feb 1 13:17:01 karanyogi CRON[43137]: (root) CMD ( cd / && run-parts --report /etc/cron.hourly) Feb 1 13:17:01 karanyogi CRON[43138]: (karanyogi) CMD (/home/karanyogi/E-Mango/env/bin/python /home/karanyogi/E-Mango/Jan27New/eMango/manage.py crontab run 60a198cfdc0c719d07735a708d42bafb >> /path/to/log/file.log # django-cronjobs for iStudyMain) Feb 1 13:17:01 karanyogi CRON[43136]: (karanyogi) MAIL (mailed 71 bytes of output but got status 0x004b from MTA#012) Feb 1 13:18:01 karanyogi CRON[43267]: (karanyogi) CMD (/home/karanyogi/E-Mango/env/bin/python /home/karanyogi/E-Mango/Jan27New/eMango/manage.py crontab run 60a198cfdc0c719d07735a708d42bafb >> /path/to/log/file.log # django-cronjobs for iStudyMain) Feb 1 13:18:01 karanyogi CRON[43266]: (karanyogi) MAIL (mailed 71 bytes of output but got status 0x004b from MTA#012) Feb 1 13:19:01 karanyogi CRON[43285]: (karanyogi) CMD (/home/karanyogi/E-Mango/env/bin/python /home/karanyogi/E-Mango/Jan27New/eMango/manage.py crontab run 60a198cfdc0c719d07735a708d42bafb >> /path/to/log/file.log # django-cronjobs for iStudyMain) Feb 1 13:19:01 karanyogi CRON[43282]: (karanyogi) MAIL (mailed 71 bytes of output but got status 0x004b from MTA#012) Feb 1 13:20:01 karanyogi CRON[43437]: … -
django count distinct values of multiple fields
I've no idea on a efficient way to count "GOOD" or "BAD" in a single Feedback.(count from all fields, mean count how many good does this Feedback has). My models.py is as class Feedback(models.Model): ... class FeedbackOption(models.TextChoices): BAD = "BAD", "Bad" GOOD = "GOOD", "Good" ... comment = models.TextField() timestamp = models.DateTimeField(auto_now_add=True, blank=True, null=True) overall_experience = models.CharField(max_length=32, choices=FeedbackOption.choices) doctor_checkup = models.CharField(max_length=32, choices=FeedbackOption.choices) staff_behavior = models.CharField(max_length=32, choices=FeedbackOption.choices) clinic_environment = models.CharField(max_length=32, choices=FeedbackOption.choices) -
ImportError: cannot import name 'CustomerIdNameSerializer' from 'contacts.api.serializers'
I have been trying to craft some unit tests for pytest. The server runs just fine when I do 'python manage.py runserver'. However, when I do 'pytest', it shows the following error: ============================ test session starts ============================= platform darwin -- Python 3.7.9, pytest-6.2.2, py-1.10.0, pluggy-0.13.1 django: settings: tradeforce.settings.dev (from ini) rootdir: /Users/woohyunan/projects/work/tradir/backend-app, configfile: pytest.ini plugins: fixture-order-0.1.3, drf-1.1.2, common-subject-1.0.5, lambda-1.2.4, django-4.1.0, assert-utils-0.2.1 collected 0 items INTERNALERROR> Traceback (most recent call last): INTERNALERROR> File "/Users/woohyunan/myvenv/lib/python3.7/site-packages/_pytest/python.py", line 578, in _importtestmodule INTERNALERROR> mod = import_path(self.fspath, mode=importmode) INTERNALERROR> File "/Users/woohyunan/myvenv/lib/python3.7/site-packages/_pytest/pathlib.py", line 531, in import_path INTERNALERROR> importlib.import_module(module_name) INTERNALERROR> File "/Users/woohyunan/.pyenv/versions/3.7.9/lib/python3.7/importlib/__init__.py", line 127, in import_module INTERNALERROR> return _bootstrap._gcd_import(name[level:], package, level) INTERNALERROR> File "<frozen importlib._bootstrap>", line 1006, in _gcd_import INTERNALERROR> File "<frozen importlib._bootstrap>", line 983, in _find_and_load INTERNALERROR> File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked INTERNALERROR> File "<frozen importlib._bootstrap>", line 677, in _load_unlocked INTERNALERROR> File "/Users/woohyunan/myvenv/lib/python3.7/site-packages/_pytest/assertion/rewrite.py", line 170, in exec_module INTERNALERROR> exec(co, module.__dict__) INTERNALERROR> File "/Users/woohyunan/projects/work/tradir/backend-app/contacts/tests/integration_tests.py", line 4, in <module> INTERNALERROR> from contacts.api.views import CustomerCreateAPIView INTERNALERROR> File "/Users/woohyunan/projects/work/tradir/backend-app/contacts/api/views.py", line 15, in <module> INTERNALERROR> from contacts.api.serializers import ( INTERNALERROR> File "/Users/woohyunan/projects/work/tradir/backend-app/contacts/api/serializers.py", line 7, in <module> INTERNALERROR> import user.api.serializers INTERNALERROR> File "/Users/woohyunan/projects/work/tradir/backend-app/user/api/serializers.py", line 20, in <module> INTERNALERROR> from contacts.api.serializers import ( INTERNALERROR> ImportError: cannot import name 'CustomerIdNameSerializer' from 'contacts.api.serializers' (/Users/woohyunan/projects/work/tradir/backend-app/contacts/api/serializers.py) … -
Environment variable not accessible in wsgi.py
I want to have different settings.py files for the production and development environments for my Django project. For that, I have permanently added an environment variable(DJANGO_ENV) in the production environment based on which I am loading different settings.py. But for some reason, wsgi.py[code below] isn't accessing the environment variable hence the if condition is failing. import os from django.core.wsgi import get_wsgi_application if os.environ.get("DJANGO_ENV") == "PROD": #*this condition is failing for some reason os.environ['DJANGO_SETTINGS_MODULE']= 'myproject.settings_prod' else: os.environ['DJANGO_SETTINGS_MODULE']= 'myproject.settings' application = get_wsgi_application() If I do echo $DJANGO_ENV on the terminal, I get "PROD" as the response, so the variable is set properly. Also in the python shell, I can access the DJANGO_ENV variable. >>> import os >>> os.environ.get("DJANGO_ENV") 'PROD' What am I doing incorrectly? -
How do we seek/backward video file that stored in Django backend?
I have a video file that plays with HTML in frontend, but I can't seek/forward/backward the video. How do I implement this feature ? Any web technologies in any language will be welcomed. I am thinking about web sockets in python and socket.io in JS. -
ModuleNotFoundError: No module named 'fcntl' django
Traceback (most recent call last): File "c:\users\sairam\appdata\local\programs\python\python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\sairam\appdata\local\programs\python\python39\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Users\sairam.virtualenvs\SEMP-VmrjoZUW\Scripts\gunicorn.exe_main.py", line 4, in File "c:\users\sairam.virtualenvs\semp-vmrjozuw\lib\site-packages\gunicorn\app\wsgiapp.py", line 9, in from gunicorn.app.base import Application File "c:\users\sairam.virtualenvs\semp-vmrjozuw\lib\site-packages\gunicorn\app\base.py", line 11, in from gunicorn import util File "c:\users\sairam.virtualenvs\semp-vmrjozuw\lib\site-packages\gunicorn\util.py", line 9, in import fcntl -
How to use Svelte + Flask (Jinja2) templates?
Summary: To use Svelte instead of jQuery in existing Flask apps. Problem: We've got an existing Flask/Jinja2 server-side rendered website. It uses jQuery. I'd like to use Svelte without SPA/Sapper/Router/etc. and just as a library. Ofcourse, Svelte is a compiled preprocessor that generates optimized vanilla JS that manages state/reactivity without shadow DOM or any other tricks that React/Angular uses. Requirements: Multipage app, cannot be SPA. Routing is not needed, we're fine with page refresh :) and no state needs to be shared between pages (except for cookies ofcourse). Impact: Svelte is great, but vast majority of enterprise and silent majority already have websites written in Flask/Django with some JS functionality (most likely jQuery). Wouldn't be great to use a preprocessor such as Svelte to add interactivity/reactivity to existing websites? Not everyone has the luxury to build SPA apps and there are other reasons for not building one (SEO for e.g.). Possible Ideas: Webpack: Preprocess Svelte app to .js file + .html file. Serve both after rendering it through Jinja2 templating engine. How Vue.js does this: How to render by Vue instead of Jinja Thoughts? I am not familiar with Webpack enough but Svelte seems to be a perfect fit for … -
Django-Upload image to MySQL Database as BLOB
Im creating an E-shop and i have an admin dashboard where i add new products in database. Currently im storing directly the product image as file, and phpmyadmin is converting it to BLOB. But this is not an efficient way to do this. So im coding a HTML page where i can send the image to backend and then upload it to the database. Im using Django Forms to register a new product as follows Forms.py class Upload_New_Product_Form(forms.Form): product_id = forms.IntegerField() name = forms.CharField(max_length=50) price = forms.DecimalField(max_digits=7, decimal_places=2) image = forms.ImageField() products.html <form method="POST" action="{% url 'upload_new_product' %}"> {% csrf_token %} <div class="input-group"> {{product_form}} </div> <br> <button type="submit" class="makeChangebtn btn-primary">Submit changes</button> </form> views.py def Upload_New_Product_View(request): if request.method == 'POST': _id = request.POST['product_id'] name = request.POST['name'] price = request.POST['price'] image = request.POST['image'] print(image) new_product = Product.objects.create(id=_id,name=name,price=price,image=image) new_product.save() When i print the image in my views.py from POST request, i get only the name of the image. What is the correct way to retrieve the image and then convert it in binary to finally store it on database? -
No migrations to apply while in makemigrations migrations are shown
Even When there are migrations to apply when making the command migrate it shows no migrations to apply -
CORS policy: Response to preflight request doesn't pass access control
Here I'm trying to run this code but i am getting CORS error when integrated with angular. this is my source code Settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'webapp', 'rest_framework', 'knox', 'django_rest_passwordreset', 'corsheaders', ] 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', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] ALLOWED_HOSTS=['*'] CORS_ORIGIN_ALLOW_ALL = True I'm adding all of these but I'm getting same error while running. Tell me the answer -
Django dynamic folder name based on id/username when uploading image
Good day SO. I want to make my folder name(s) to be renamed based on the ID/username of the uploader. My setup is as follows: class Account(AbstractBaseUser): username= models.CharField(...) # As per our setup, user cant enter their own username but will be auto created based on a separate py file on my view during registration ... class Type01Account(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE) ... imgPath = "" images= models.ImageField(upload_to=imgPath, null=False, blank=False) How should I assign imgPath? Should I assign it on models or on view? If so, how should I save it? -
Having a unqiue counter per User for a different model in Django
I would like to know what the best way to have a model Receipt where the model has an ID field that is unique to each Django User, that won't have issues with asynchronous requests. There is still a separate main ID field added by default, but I would like to have a separate ID for the receipts so that I can display this ID for each User so that their receipt numbers start from 1 when they go to their receipt list. class Receipt(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) employee = models.CharField(max_length=255) date = models.DateTimeField() txn_type = models.CharField(max_length=8) total = models.DecimalField(max_digits=10, decimal_places=2) correction = models.ForeignKey( ReceiptCorrection, on_delete=models.PROTECT, default=None, null=True I understand you can check the last number and then just increment by one, but won't that have issues if two computers are running the same user and they both make a receipt at the same time? I appreciate any help with this. Thank you! -
How to read .env file in django celery
I used celery (5.0.5), django (3.1.1), django-dotenv project structure Project api ----task.py config ----settings.py ----celery.py manage.py Typing celry -A config worker -l INFO results in an error I don't seem to be able to read the .env file Because it works fine in db.splite3 I tried adding the code dotenv.read_dotenv(env_file) in celery.py. But it didn't work. What am I missing? > celery -A config worker -l INFO Traceback (most recent call last): File "/Users/junyoung/Dev/notification-drawer-api/venv/bin/celery", line 10, in <module> sys.exit(main()) File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/celery/bin/celery.py", line 213, in main return celery(auto_envvar_prefix="CELERY") File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/click/core.py", line 829, in __call__ return self.main(*args, **kwargs) File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/click/core.py", line 782, in main rv = self.invoke(ctx) File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/click/core.py", line 1259, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/click/core.py", line 1066, in invoke return ctx.invoke(self.callback, **ctx.params) File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/click/core.py", line 610, in invoke return callback(*args, **kwargs) File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/click/decorators.py", line 21, in new_func return f(get_current_context(), *args, **kwargs) File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/celery/bin/base.py", line 132, in caller return f(ctx, *args, **kwargs) File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/celery/bin/worker.py", line 320, in worker worker = app.Worker( File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/celery/worker/worker.py", line 94, in __init__ self.app.loader.init_worker() File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/celery/loaders/base.py", line 111, in init_worker self.import_default_modules() File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/celery/loaders/base.py", line 105, in import_default_modules raise response File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/celery/utils/dispatch/signal.py", line 276, in send response = receiver(signal=self, sender=sender, **named) … -
django how to loop in view and print in template
i have serial numbers in my database , each serial number have coded date in it, i want to get the date from the serial number and print in data table my view.py from .models import Module month = {'1': 'Jan', '2': 'Feb', '3': 'Mar', '4': 'Apr', '5': 'May', '6': 'Jun', '7': 'Jul', '8': 'Aug', '9': 'Sep', '10': 'Oct', '11': 'Nov', '12': 'Dec'} year = {'L': '2010', 'M': '2011', 'N': '2012', 'O': '2013', 'P': '2014', 'Q': '2015'} @login_required() def modules(request): modules = Module.objects.all() for module in modules: day = module.serial_number[:2] mon = module.serial_number[2:3] mon = [val for key, val in month.items() if mon in key] year1 = module.serial_number[3:4] year1 = [val for key, val in year.items() if year1 in key] print(module.serial_number, day, mon, year1) total_modules = modules.count() context = {'modules': modules, 'total_modules': total_modules, } return render(request, 'modules/modules.html', context) when print(module.serial_number, day, mon, year1) im getting what i want 044PGG01501S 04 ['Apr'] ['2014'] 127QGG01501S 12 ['Jul'] ['2015'] but cant make this work in template any ideas -
Override admin_menu.py file in django admin panel for sidebar customization
There is a file called admin_menu.py in django_adminlte_theme>templatetags. This file is used for customization of sidebar of django admin panel i.e. dropdowns menus are their order Everything is set except the main thing i.e. override this, right now I am doing this by overriding i the base file which came on the installation and we cannot upload this with other files on server. I have tried a few things like changing the templates directory in settings.py, adding site-packages or django-adminlte-theme folder in my project directory Is their anyway of doing this??? Thankyou in advance -
GET urls with different path params in DRF
I need 2 GET urls in my DRF application myapp/members/{id}/benefits myapp/members/{member_number}/benefits And i need to redirect it to 2 different viewsets also myapp/members/{id}/benefits - Viewset1 myapp/members/{member_number}/benefits - Viewset2 Is that possible. If yes, how can I design my urls.py? -
PostgreSQL and My Django app on heroku is not synching
I have a django made app on heroku and I want change the database there from sqlite to postgreSQL. I have changed the code in setting.py as follows however the data in my local sqlite is still uploaded to heroku. from socket import gethostname hostname = gethostname() if "MY-COMPUTER-NAME" in hostname: #my computer name # debug # DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } ALLOWED_HOSTS = ['*'] else: # online # DEBUG = False import dj_database_url db_from_env = dj_database_url.config() DATABASES = { 'default': dj_database_url.config() } ALLOWED_HOSTS = ['*'] My commands to deploy git add -A git commit -m "Change" git push heroku master heroku ps:scale web=1 heroku run python manage.py migrate heroku open this is a full code of srtting.py import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ":)" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ … -
I want to display registered person details like (first name , email , phone number) in profile.html page page - django
I want to display registered person details like (first name, email, phone number) in profile.html page page... what is the code use in views.py file.. can anyone help me Here is registered table in models.py class Register(models.Model): fullname=models.CharField(max_length=60) companyname=models.CharField(max_length=60) Email=models.CharField(max_length=50) password=models.CharField(max_length=12) contactno = models.CharField(max_length=30) I want to display these details in profile.html page Here is my views.py file for profile def profile(request): return render(request, 'web/profile.html') -
how to implement wishlist to have unknown number of items - Django
I want to implement a wishlist for my online shop project which is a Django project. I already implemented WishListItem table and due to my scenario, I used GenericForeignKey: class WishListItem(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50, null=True, blank=True) count = models.IntegerField(null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) add_to_list_date = models.DateTimeField(_('add to list date'), null=True, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return self.title now I have to implement Wishlist table. 1- the user may have many wishlists. 2- each wish list have an unknown number of WishlistItemss. here is what I have in mind: class QuoteList(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) message = models.CharField(max_length=200) item = models.ForeignKey(WishListItem, on_delete=models.CASCADE) but I know it's not quite good. how to add many wishlistitems to one quotelist? -
How to get suggestion with a model field
I want to get suggestions in user end with order given by field following with Alphabetical order. I have written a view where now I am getting suggestion in Alphabetical order class ParentIndustry(models.Model): name = models.CharField(max_length=285, blank=True, null=True) date_added = models.DateTimeField(null=True, blank=True, auto_now_add=True) date_modified = models.DateTimeField(null=True, blank=True, auto_now=True) status = models.IntegerField(default=0) sort_data = models.IntegerField(default=0) modified_by = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return str(self.name) class Meta: verbose_name_plural = "Parent Industries" I want to get suggestion with field value sort_data = 0,1,2,3,4,5 after assigning a value in admin. Now I am getting data in User End from ascending to descending (Alphabetical order) with below view function. def industry_list_suggestion(request): name = request.GET.get('q') industry = request.GET.getlist('industry[]') if name is None: filters = models.Q() company_results = ParentIndustry.objects.filter(filters,status='1').order_by('name','-id').values('name','id').exclude(name__isnull=True).distinct('name') page = request.GET.get('page', 1) paginator = Paginator(company_results, 10) try: results = paginator.page(page) except PageNotAnInteger: results = paginator.page(1) except EmptyPage: results = paginator.page(paginator.num_pages) total_count = company_results.count() company_results = list(results) results = {'total_count':total_count,"items":company_results,"value":"market"} return JsonResponse(results,safe=False) if name is not None: term = request.GET.get('q') filters = models.Q() filters &= models.Q( name__istartswith=term, ) sources_objects_suggestion = ParentIndustry.objects.filter(filters,status='1').order_by('name','-id').values('name','id').exclude(name__isnull=True).distinct('name') page = request.GET.get('page', 1) paginator = Paginator(sources_objects_suggestion, 10) try: results = paginator.page(page) except PageNotAnInteger: results = paginator.page(1) except EmptyPage: results = paginator.page(paginator.num_pages) total_count = … -
Django Rest API. Get all data from different models in a single API call
I am trying to get all data related to model Post using one single API call. This call should include post contents, comments, upvote and downvotes. I have 4 models and Post model is a foreign key to every other model. class Post(models.Model): title = models.CharField(max_length=200, null=True, blank=True) body = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return str(self.title) class UpVote(models.Model): post = models.OneToOneField(Post, related_name="upvote_post", on_delete=models.CASCADE) upvotes = models.IntegerField(default=0) class DownVote(models.Model): post = models.OneToOneField(Post, related_name="downvote_post", on_delete=models.CASCADE) downvotes = models.IntegerField(default=0) class Comment(models.Model): post = models.ForeignKey(Post, related_name="comment_post", on_delete=models.CASCADE) comment = models.CharField(max_length=200, null=True, blank=True) I saw this solution in a post to combine data with a foreign key relationship that exists. class UpVoteSerializer(serializers.ModelSerializer): class Meta: model = UpVote fields = "__all__" class DownVoteSerializer(serializers.ModelSerializer): class Meta: model = DownVote fields = "__all__" class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = "__all__" class PostSerializer(serializers.ModelSerializer): upvote = UpVoteSerializer(read_only=True, many=False) downvote = DownVoteSerializer(read_only=True, many=False) comments = CommentSerializer(read_only=True, many=True) class Meta: model = Post fields = ("id", "title", "body", "upvote", "downvote", "comments") This is from the views.py file @api_view(['GET']) def postList(request): post = Post.objects.all().order_by('-id') serializer = PostSerializer(post, many=True) return Response(serializer.data) This is the output that get returned [ { "id": 7, "title": "1st post", "body": "Body of 1st post" … -
How do I correctly render sqlite3 data on my html Django
This is the code for getting the data inside my database, basically I want to get the winning bid of each open listing, but when I render on the html it look wrong. NEED Want the request.user close listing and then show the winning bid of that close listing Correct HTML rendering view.py def closebidview(request): if request.user.is_authenticated: listings = request.user.listing_set.all().filter(open_at=False) bid_data = [] for i in request.user.listing_set.all().filter(open_at=False): bid_data.append(i.bid.order_by("-date").first()) return render(request, "auctions/closebid.html", { "listings": listings, "bids": bid_data }) else: return render(request, "auctions/closebid.html") closebidview.html {% extends "auctions/layout.html" %} {% block body %} <h2>Closebid {{ request.user.username }}</h2> {% if user.is_authenticated %} <div style="display: flex;"> {% for listing in listings %} <div class="card-deck" style="width: 18rem; padding: 2px;"> <div class="card"> <img class="card-img-top" src="{{ listing.image.url }}" alt="{{ listing.title }}"> <div class="card-body"> <h5 class="card-title">{{ listing.title }}</h5> <p class="card-text">{{ listing.description }}</p> <p class="card-text"><strong>Price: ${{ listing.starting_price }}</strong></p> {% if user.is_authenticated %} {% for bid in bids %} {{ bid.user }} <p>{{ bid.user.username }} is the winner</p> <p>Contact:</p> <ul> <li>{{ bid.user.email }}</li> </ul> {% endfor %} {% else %} <p><a href={% url 'login' %}>Login</a> to see the winner!</p> {% endif %} </div> <div class="card-footer"> <small class="text-muted">{{ listing.create_at }} by: {{ listing.owner.username }}</small> </div> </div> </div> {% empty %} <h1>{{ request.user.username … -
How to access 2 different model filefields in View and copy paste data from one file to the other
I have 2 models with filefield: from django.db import models from django.db.models import Model class ExcelModel(Model): Excel_file = models.FileField() file_name = models.CharField(max_length=100, default='lolcakes') class CsvModel(Model): csv_file = models.FileField() file_name = models.CharField(max_length=100, default='meow') In view, I want to access each file and copy the value in row 1 and column 1 inside the meow csv file, to the excel file. I am looking into using Openpyxl for this but I cannot get past accessing the file. -
Manager used in django query
Is it possible to get the name of the manager used in making a query. say for example I did; x = Products.objects.first() y = Products.some_objects.first() where some_objects is a custom manager, would it be possible to get objects and some_objects as the manager used in making the query?