Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i want to display registered person values to another html page in django
i have member table for registration.. i want to display that table values(like firstname,lastname, email etc..) in another page (only registered person values ) i tried with id.. if i give id means only that particular value is displaying... but i want registered person values this is my member table class Member(models.Model): firstname=models.CharField(max_length=30) lastname=models.CharField(max_length=30) Email=models.CharField(max_length=50) password=models.CharField(max_length=12) Thanks for your time. -
DRF: Set ImageField to not required in external serializer
UserSerializer contains an ImageField, which is set to blank=True, null=True and a default picture URL is given. In my OtherSerializer, I try to get the ImageField into it via: class OtherSerializer(serializers.ModelSerializer): user_image = serializers.SerializerMethodField() class Meta: model = OtherModel fields = ('user_image') def get_user_image(self, obj): return obj.find_user_and_all_that_stuff_not_an_actual_method.image However, when I try to call the data from OtherSerializer, I get: image attribute has no file associated with it. Any way I can set required = False, if the field is external and doesn't have that parameter? -
Program not parsing whole in POST method
I am getting " AssertionError: 'CouponValidationView' should either include a serializer_class attribute, or override the get_serializer_class() method." when i click on API link but when i put 'serializer_class' in my django class based viewset, program do not parse through subsequent function it just get over after serializer_class() method. Here is my views.py file : class CouponValidationView(viewsets.ModelViewSet): queryset = Coupon.objects.all() serializer_class = CouponSerializer def get(self, request, code, format=None): try: coupon = Coupon.objects.get(code=code) except ObjectDoesNotExist: return Response( data={"message": "Success"}, status=status.HTTP_404_NOT_FOUND ) serializer= CouponSerializer(coupon) resp = {"data": serializer.data, "message": "Failure"} return Response(resp, status=status.HTTP_200_OK) Please do Help -
Django Admin Model Thousand Separator in Change form when using Grappelli extension
I am working on an internal Django project using the Grappelli Admin Theme. I am in Australia and would like to format decimal numbers above 999 as 1,000.00 2,000.00. I have added the following to my settings.py file and the Model field has been defined as a Decimal. The Change List form displays the number correctly formatted. However, the changeform does not and retains the unlocalized format. LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Australia/Queensland' USE_I18N = True USE_L10N = True USE_THOUSAND_SEPARATOR = True NUMBER_GROUPING = 3 I have found numerous similar posts such as Make Django forms use comma as decimal separator And it does state localization does need to be turned on explicitly for every field. For a model form (including the ones used in the admin app), a convenient way to do this is to subclass ModelForm and turn on localization for each DecimalField However, at this stage I just need the Admin Change Form to carry the localisation and I am not sure how to do this when the Grappelli extension is in play. And as I have mentioned the Change List Form does render the same field with the thousand separator as I had hoped. Your thoughts … -
how can i send email using djcelery
here i am using djangorestframework and i am trying to send email using celery whenever is trying to login with a report but i am getting smtp error every time i have used api view serialiazer and trying to send email whoever login i couldn't understand what is my error and did i wrote the tasks.py correctly settings.py """ Django settings for MyMovie project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) import djcelery djcelery.setup_loader() # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '=g9h-vb%r2^_lngqh_mn3y29g2n_7zvfkj(ysshs#hv5pbj0=%' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'knox', 'djcelery', 'django_celery_beat', 'TestApp' ] 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', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ # 'rest_framework.authentication.BasicAuthentication', # 'rest_framework.authentication.SessionAuthentication', 'knox.auth.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] } ROOT_URLCONF = 'MyMovie.urls' TEMPLATES … -
raise EnvironmentError( OSError: pdftotext not installed. Can be downloaded from https://poppler.freedesktop.org/) in python
I am using the invoice2data library to extract data from the invoice and getting this error... > Traceback (most recent call last): File "C:\Users\{user-name}\Envs\django\lib\site-packages\django\core\handlers\exception.py", > line 47, in inner > response = get_response(request) File "C:\Users\Abhishek Saini\Envs\django\lib\site-packages\django\core\handlers\base.py", > line 179, in _get_response > response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\stuff\pdf_reader\pdf_processing\structuredpdf\views.py", line 41, > in fileUpload > pdf = extract_data(str(files.name),templates=read_templates("invoice/")) > File "C:\Users\Abhishek > Saini\Envs\django\lib\site-packages\invoice2data\main.py", line 82, in > extract_data > extracted_str = input_module.to_text(invoicefile).decode('utf-8')File "C:\Users\{user- name}\Envs\django\lib\site-packages\invoice2data\input\pdftotext.py", > line 29, in to_text > raise EnvironmentError( OSError: pdftotext not installed. Can be downloaded from https://poppler.freedesktop.org/ I already install pdftotext and tried reinstalling anaconda and poppler but got the same error what should I do now -
django static error in bash linux command
File "/usr/lib/python3.7/os.py", line 221, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/static' -
Failure: Azure GitHub Deployment for Django-React Web App
I'm completely new to Azure and I deployed my Django-React web app. It says the deployment was successful, however, on the actual web address, it says the application failed. I have a few dumb questions: In the settings.py file that's in the GitHub repo, I removed the security key and database password for security reasons. Is that the issue? The runtime stack is Python 3.8, but could that be an issue since the frontend is react.js? What are HTTP errors 503 and 502 associated with? -
Django POST data from admin not being displayed
So I have looked over this so many times now and cannot seem to find the issue for the life of me. Not only does it not display the database information that it queried for, I cannot seem to add anything to it through the form. The views.py method I have is supposed to either render all the info into the divs, yet it renders the right amount of divs with no information in it. Also, the post request goes through as i can see on cmd, but the database remains unchanged, and no changes are made to the HTML. please i could use some help. views.py from django.shortcuts import render from .models import Note def notes(request): if request.method == "POST": new_note = request.objects.all() Note.objects.add(new_note) return render(request, "notebook/notes.html", { "notes": Note.objects.all() }) models.py from django.db import models class Note(models.Model): title = models.CharField(max_length=64) content = models.CharField(max_length=300) def __str__(self): return f"{Note.title} {Note.content}" layout.html(just the relevant part) <div class="card content"> <div class="card-body"> <h4 class="card-title" style="font-weight: bold;"> Post A New Note </h4> <form action="{% url 'notebook:notes' %}" method="post"> {% csrf_token %} <div class="input"> Note Title </div> <div><input name="title" style="margin-top: -10px;"></div> <div class="input">Note Content </div> <div><input class="note_txt" name="content"></div> <div class="row"> <input class="btn" type="submit" style="margin-top: 20px;"> … -
Packaging my Django Application to Windows Installer
I have a Django application, and it is working fine with Apache and MySQL. Now I need to distribute it as a windows installer. I normally use Ubuntu, so I don't know much about creating a windows installer. The installer basically should do the below things. Extract the package ( I am thinking of packaging my application, python(with all the dependencies installed), Apache, and MySQL in the package) Set the Env Variables for Python referring to the python in the package. Install or Extract Apache and configure the same to point to my application. Install MySQL. Create DB and run manage.py migrate. Bring up the apache, The targeted end users are just laymen, so the installation process should as installing a windows application. Request you to please suggest on the best way package the same. -
django queryset to select max id of each distinct filed
I'm new to django, and I want to select last message of each thread: models.py class ChatMessage(models.Model): thread = models.ForeignKey('Thread', null=True, blank=True, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="sender", on_delete=models.CASCADE) message = models.TextField(null=True) timestamp = models.DateTimeField(auto_now_add=True) voice = models.FileField(upload_to=upload_voice_dir, blank=True, null=True) I'v no idea how to filter(I just know basics of filtering). to sum it up I want the last message of each thread. -
Filtering multiple data in Django
I want to retrieve multiple value based on their data value below. Currently what I did is I've been using for loop below but it only retrieve one value and I want to update based on the looping result.It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance @login_required(login_url='log_permission') def archive_folder(request): if request.method == 'POST': data_id = request.POST.get('id') #single value only example we have: 6 data = gallery_photos.objects.filter(gallery_info_id = idd) # multiple value example we have 3 rows for sample in data : viewing= sample.photos # I want to retrieve those three rows based on their photos column value in database Person.objects.filter(path = viewing).update(path=None) return JsonResponse({'data': 'success'}) -
NameError at /HomeFeed/ name 'slug' is not defined
NameError at /HomeFeed/ name 'slug' is not defined Is there a way for me to define slug without changing my url? def home_feed_view(request, *args, **kwargs): context = {} blog_post = get_object_or_404(BlogPost, slug=slug) context['blog_post'] = blog_post return render(request, "HomeFeed/snippets/home.html", context) path('', home_feed_view , name= "main"), class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False, unique=True) body = models.TextField(max_length=5000, null=False, blank=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) -
How can i add choice if some choice is entered in django?
problem_choice = ( ("ford", 'Ford'), ('lambroghini', 'Lambroghini'), ) model_lamb = ('AVENTADOR.', 'AVENTADOR S.', 'AVENTADOR S ROADSTER.', 'AVENTADOR SVJ') model_ford = ('t', 'b', 'd') problem_name = models.CharField(max_length=10, choices=problem_choice, default='Ford') # if some choice is taken use that and make another choice in database I want to have Lambroghini model come out in another choice fields, If lambroghini is choosen and so for ford. Is there any way to do this inside django models? Thank you -
Function in Django model not updating and saving corresponding field
Trying to set-up a function inside the model below to count the length of an ArrayField whenever the instance is updated. The function def total_stocks_calc() doesn't update the model, it's useless. class Bucket(models.Model): stock_count = models.IntegerField(blank=True, null=True) stock_list = ArrayField(models.CharField(max_length=6,null=True),size=30,null=True, blank=True) objects = models.Manager() def total_stocks_calc(self): self.stock_count = len(Bucket.objects.get(self.id).stock_count) self.save() I'm not getting any errors as well, however this works in django shell: len(Bucket.objects.get(id=1).stock_count), I get the corresponding amount of items within the object. Would that be the best way to accomplish a Count or Length of total strings within the ArrayField known as stock_count? -
Trying to compare current time to expiration date and return true if within 7 days:
I am writing a Pantry Inventory app for a school project with a Django backend, a DjangoRest API and a Vue2 frontend. I am trying to discern if an item is within one week of the expiration date tied to each of the items, and change expiring_soon to true if it is. My model in Django takes the expiration date through a DateTimeField that is serialized as such: class PantrySerializer(serializers.ModelSerializer): owner_detail = NestedUserSerializer(read_only=True, source='owner') expiration_date = serializers.DateTimeField(format="%d-%m-%Y") class Meta: model = models.PantryItem fields = ( 'id', 'item_name', 'create_date', 'expiration_date', 'owner', 'owner_detail', 'getting_low', 'tag', 'category', 'quantity', 'to_grocery', 'slug', 'amount_type', 'expiring_soon', 'brand', ) After browsing some related questions I've tried this as a Vue method in my root app. I call it in the created section.: getExpiry: function() { var one_day=1000*60*60*24; var currentTime = new Date() for (let i = 0; i < this.pantryItems.length; i++) var exdate = this.pantryItems[i].expiration_date; var diff = Math.ceil((exdate.getTime() - currentTime.getTime())/one_day); if (diff <= 7) { this.pantryItems[i].expiring_soon = true updateItem() } }, gettingLow: function(item) { item.getting_low = true } It gives me this error: VM22198 vue.js:634 [Vue warn]: Error in created hook: "TypeError: Cannot read property 'getTime' of undefined" (found in <Root>) warn @ VM22198 vue.js:634 logError @ … -
Django Question - Should i start a new project in the same virtual environment?
Django newbie here. I have an existing Django virtual environment that was setup as part of a tutorial, using Django 2.2. and Vagrant + Virtual Box on my laptop. There was 1 project created for the tutorial above. I will now be starting another Django tutorial, wherein I will be creating a few more projects. WHat is the best way to go about this? Should I create a new virtual environment for tutorial #2? Or use the existing environment, that was setup for tutorial #1? FYI - tutorial #2 uses Django 1.11 Thanks a lot! -
Can't get the data from HTML page by using request.GET.get
I need a simple search form in my Django app. The code is: in HTML file: <html> <body> <h2><a href="/tube">Hypertube</a></h2> <a target="_blank" href="/login/"> Log In</a> <p><form action="tube/" method="GET"> <input name="q" placeholder="Search..."> <input type="submit" value="search"> </form></p> <p><a href="/tube/tag= {{ da_tag }}/">{{ da_tag }}</a></p> <p> {{ len }} videos</p> {% for video in videos %} <div><a href="/tube/watch/{{ video.id }}/">{{ video.video.title }}</a></div> {% endfor %} <p><a target="_blank" href="/tube/upload/">Upload video</a></p> </body> </html> in views.py: class MainPageView(ListView): def get(self, request): query = request.GET.get('q') if query is not None: videos = Video.objects.filter(Q(title__icontains=query)) else: videos = VideoTag.objects.all() return render(request, 'index.html', context={'videos': videos, 'len': len(videos)}) The problem is that 'query' is None. How can I fix this? -
Django request.user.id 'matching query does not exist' error in webhook
I'm building a Stripe webhook in my Django app that, after the payment is confirmed, retrieves the current user's ID in the database and uses it to assign a subscription to the team that that user is assigned to. There are a few database tables that are important to note here: User (a custom user model for my app) Team (an organization-style model table that contains team names and a ManyToManyField with the User table "through" to the Membership table) Membership (the "through" table that contains foreign keys to the user, team, and Stripe customer tables) StripeCustomer (the Stripe customer information table that has a OneToOneField with the Team table, and stores the Stripe customer ID and subscription ID) After the payment is confirmed in the Stripe webhook, I want to pull the current user's ID from the User table using request.user.id and use it with the Membership table to get an object containing the current user's team (so that the Stripe subscription can be assigned to that team). The problem is that, when I use request.user.id within Membership.objects.get(user_id=request.user.id), I receive an error in the console stating that the "Membership matching query does not exist." However, if I just print … -
Django error only when deployed on PythonAnywhere: "No category matches the give query"
I have deployed My Django website via PythonAnywhere.com and everything seems to be working other than my search bar which gives me the the following error even if the item does exist. You can reproduce the error by going to https://www.ultimatecards5.com/ and searching for anything in the search bar. Although, when I run my project locally and do the same exact search I get the desired result of "0 results found" or a found result if it exists. Below are the error on the live page and then the same function when ran locally: The error says raised by shops.views.allProductCat My shops views.py def allProdCat(request, c_slug=None): #used to show all products in that category c_page = None #for categories products_list = None if c_slug!=None: c_page = get_object_or_404(Category,slug=c_slug) products_list = Product.objects.filter(category=c_page,available=True) #filtering products according to category else: products_list = Product.objects.all().filter(available=True) ''' Paginator Code ''' paginator = Paginator(products_list,12) #limiting 6 products per category page try: page = int(request.GET.get('page','1')) #converting GET request to integer i.e page number 1 so we can store it in page variable except: page = 1 try: products = paginator.page(page) except (EmptyPage, InvalidPage): products = paginator.page(paginator.num_pages) return render(request,'shop/category.html',{'category':c_page,'products':products}) My Shops urls.py from django.urls import path from django.contrib import admin … -
Is the server running on host "db" and accepting TCP/IP connections on port 5432?
I have a Django project and a postgres database but I cannot dockerize that. Here is the docker-compose.yml : version: '3' services: database: image: postgres restart: always env_file: - database.env web: build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py createsu && python manage.py runserver 0.0.0.0:8000" volumes: volumes: - .:/code ports: - "8000:8000" depends_on: - database Here my Dockerfile : FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ And my database.env : # database.env POSTGRES_USERNAME=admin POSTGRES_PASSWORD=pass POSTGRES_DBNAME=db POSTGRES_HOST=database POSTGRES_PORT=5432 PGUSER=admin PGPASSWORD=pass PGDATABASE=db PGHOST=database And here are the parameters from the settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db', 'USER': 'admin', 'PASSWORD': 'pass', 'HOST': 'database', 'PORT': '5432', } } But I got that : django.db.utils.OperationalError: FATAL: password authentication failed for user "admin" Could you help me please ? Thank you very much ! I precise I created my database. -
Django load JSON data into model
I'm trying to load json data file and create Player class according to the json data. For models.py I have player class class Player(models.Model): pos = models.CharField(max_length=2, default="") name = models.CharField(max_length=30, default="") age = models.PositiveIntegerField() posRank = models.PositiveIntegerField() throwAtt = models.PositiveIntegerField() throwYd = models.PositiveIntegerField() throwTD = models.PositiveIntegerField() interception = models.PositiveIntegerField() rushAtt = models.PositiveIntegerField() rushYd = models.PositiveIntegerField() rushTD = models.PositiveIntegerField() rushAvgYd = models.FloatField() target = models.PositiveIntegerField() rec = models.PositiveIntegerField() recYd = models.PositiveIntegerField() recAvgYd = models.FloatField() recTD = models.PositiveIntegerField() totalTD = models.PositiveIntegerField() fumble = models.PositiveIntegerField() fpts = models.FloatField(null=True) ppr = models.FloatField() totGames = models.PositiveIntegerField() and for serializers.py I have player serializer written as below class PlayerSerializer(serializers.ModelSerializer): class Meta: model = Player fields = ('name', 'pos', 'age', 'posRank', 'throwAtt', 'throwYds', 'throwTD', 'interception', 'rushAtt', 'rushYd', 'rushTD', 'rushAvgYd', 'target', 'rec', 'recYd', 'recAvgYd', 'recTD' 'totalTD', 'fumble', 'fpts', 'ppr', 'totGames') and inside views.py i have this class class PlayerView(generics.CreateAPIView): players = Player.objects.all() serializer = PlayerSerializer(players, many=True) def get(self, request): output = json.load('api/NewNFLdata.json') for player in output: newPlayer = Player(pos=player["FantPos"], name=player["Player"], age=player["Age"], posRank=player["PosRank"], throwAtt=player["Att"], throwYd=player["Yds"], throwTD=player["TD"], interception=player["Int"], rushAtt=player["Att.1"], rushYd=player["Yds.1"], rushTD=player["TD.1"], rushAvgYd=player["Y/A"], target=player["Tgt"], rec=player["Rec"], recYd=player["Yds.2"], recAvgYd=player["Y/R"], recTD=player["TD.2"], totalTD=player["TD.3"], fumble=player["Fmb"], fpts=player["FantPt"], ppr=player["PPR"], totGames=player["G"] ) newPlayer.save() return Response(serializer.data) I tried to do it by my own by looking up stack overflow … -
Graphene Django Image Field showing wrong path
I am trying to switch my axios queries to graphene-django but my images is mixed with both full path and server path: This is my schema: class ArticleType(DjangoObjectType): class Meta: model = Article fields = ("slug", "title", "excerpt", "content", "image") image = graphene.String() def resolve_image(self, info): """Resolve product image absolute path""" if self.image: self.image = info.context.build_absolute_uri(self.image) return self.image class Query(graphene.ObjectType): all_articles = graphene.List(ArticleType) def resolve_all_articles(self, info, **kwargs): return Article.objects.all() in graphiql the response is { "errors": [ { "message": "[Errno 2] No such file or directory: '/home/ytsejam/public_html/lockdown/yogavidya/media/http:/localhost:8000/graphql/5_135818877_742799629979350_7327381988945830866_o.jpg'", "locations": [ { "line": 6, "column": 5 } ], "path": [ "allArticles", 0, "image" ] }, ... ]} How can I fix my correct path ? Thanks -
How can I add a second dependent field to my current Django dependent drop down form?(Car Makes/Models/Years
Context I'm currently building a car dealership app and am struggling on a dependent search form. At the moment, it takes the users make selection and returns a list of models belonging to it that exist in the db. However now I am struggling to make a second dependent field where available years are provided based on the model chosen. Attempts Made The question text will already be very long with just the Ajax but essentially, I've tried creating a duplicate Ajax request,view and url with slightly different names and targeting the carmodel but all I got was no errors and no results. I've tried rendering two dicts from the one request which did actually get me the years to log in the console but I couldn't join the two dicts successfully nor could I work out how to render the years when I got them to log. I went over everything line and understand when/how/why it's targeting certain id's and creating new options for the form but I just can't get it to work when the model is chosen after the make. Code Here is a view of my models.py class CarMake(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name … -
How to load static files on heroku server?
I have successfully deployed my django project on heroku but my project is not looking as it looks on local server due to static files i guess. I am using django 3.1.4. And having issues with version control. here what its look on local : here what its look on server : settings.py: STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_ROOT = BASE_DIR / 'staticfiles' STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", '/var/www/static/', ]