Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When deploying Django to Heroku: ModuleNotFoundError: No module named 'dotenv'
When deploying Django to Heroku, I get a ModuleNotFoundError: No module named 'dotenv' error. However, I do have python-dotenv listed in my requirements.txt. So I'm very confused about why Heroku is not happy about dotenv. Here is my requirements.txt: cffi==1.14.2 cryptography==3.1 dj-database-url==0.5.0 Django==3.1.1 django-cors-headers==3.5.0 django-heroku==0.3.1 django-rest-knox==4.1.0 django-simple-email-confirmation==0.70 djangorestframework==3.11.1 gunicorn==20.0.4 psycopg2==2.8.6 pycparser==2.20 python-dotenv==0.14.0 pytz==2020.1 six==1.15.0 sqlparse==0.3.1 whitenoise==5.2.0 -
Django admin filter – filter annotated relations
app.models class Courier(models.Model): pass class Order(models.Model): courier = models.ForeignKey(Courier, related_name='orders') class Delivery(models.Model): order = models.OneToOneField(Order) date = models.DateTimeField() # app.admin @admin.register(Courier) class CourierAdmin(admin.ModelAdmin) list_display = ('id', 'delivered_orders_count') list_filter = ('orders__delivery__date',) def get_queryset(self, request): return super().get_queryset(request).annotate( delivered_orders_count=Count( 'orders', filter=Q(orders__delivery__isnull=False) ) ) After filtering counted objects are the same. How can I filter orders to count against courier list? -
Django Rest Framework, how to get number of objects of foreignkey inside another foreignkey
I have three models Store, Product and Order class Store(models.Model): ...... class Product(models.Model): store = models.ForeignKey(Store, ...) class Order(models.Model): product = models.ForeignKey(Product ...) delivered = models.BooleanField() I want to create a @property for the Store model that calculates the number of orders that has its products and also has delivered=True how will i go about in doing that? -
Is it possible in Wagtail to use a proxy model with RoutablePageMixin?
My Wagtail site has certain items viewable in a gallery app, that the user can edit so that it would be also shown as an item in the shop app. It's strictly one-to-one, so I don't want them to be managing the items separately. I thought proxy models might be the best way to achieve this but I'm getting stuck and not finding very much documentation about using proxy models with Wagtail. Also possibly my regex is bad. In app 'gallery': class GalleryItem(Page): parent_page_types = ['InstallationPage'] description = models.CharField(blank=True, max_length=250) direct_sale = models.BooleanField("Direct Sale", default=False, help_text="Check this box to list this item for sale directly on your website.") direct_sale_price = models.DecimalField("Sale price, $", blank=True, null=True, max_digits=6, decimal_places=2, help_text="Add more info about this item for the store page only.") direct_sale_extra_description = models.CharField("Addtional sale description (optional)", blank=True, max_length=250, ) stock = models.IntegerField("Number in stock", blank=True, null=True,) In app 'shop': from gallery.models import GalleryImage class Shop(Page): def get_context(self, request): context = super().get_context(request) shop_items = ShopItem.objects.filter(Q(direct_sale=True) | Q(external_sale=True)) paginator = Paginator(shop_items, 24) page = request.GET.get('page') try: pagin = paginator.get_page(page) except PageNotAnInteger: pagin = paginator.get_page(1) context['shop_items'] = shop_items return context class ShopItem(GalleryItem, RoutablePageMixin): class Meta: proxy = True parent_page_types = ['Shop'] @route(r"^shop/(?P<item_slug>[-\w]*)/$", name="item_view") def item_view(self, … -
Get Options from Models post on Html Django
I'm having some issues trying to get the list out of the model and print it dynamically on my HTML view. Here's what I've done so far, and what I've got as view. models.py class Projeto(models.Model): acoes = ( ('', "---------"), ('Projeto', "Projeto"), ('Evento', "Evento"), ('Curso', "Curso"), ) areas = ( ('', "---------"), ('Comunicação', 'Comunicação'), ('Cultura', 'Cultura'), ('Direitos Humanos e Justiça','Direitos Humanos e Justiça'), ('Educação', 'Educação'), ('Meio Ambiente', 'Meio Ambiente'), ('Saúde', 'Saúde'), ('Tecnologia e Produção', 'Tecnologia e Produção'), ('Trabalho', 'Trabalho'), ) views.py def lista_projetos(request): projetos_unemat = Projeto.objects.order_by('id') page = request.GET.get('page', 1) paginator = Paginator(projetos_unemat, 10) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) lista_acoes = Projeto.acoes lista_areas = Projeto.areas context = { 'projetos': users, 'acoes': lista_acoes, 'areas': lista_areas } return render(request, 'lista_projetos.html', context) _filter.html <div class="container"> <div class="row justify-content-md-center"> <select class="form-control col-4" id="acoes"> {% for acao in acoes %} <option name="{{acao}}"> {{acao}} </option> {% endfor %} <div class="input-group-append"> <button class="btn btn-outline-secondary fas fa-search" type="submit"></button> </div> </div> And my page shows this: page view How do I get to show only the options? -
Best way to view data in django rest framework database?
I have tried to connect from PyCharm database tool to the mySQL django database and without success. By doing so - what is the best configuration for the tool? The image below shows my configuration with the apropriate error. What are the best practices to view data? Maybe ER-diagrams and stuff? -
Can't use FormData in UI material forms to fetch form field values
I am just trying to post data from my UI-material form into backend. I am using react hooks here. Below is code that i am trying to do using simple fetch. const [name, setName] = useState (''); const [email_id, setEmail] = useState (''); const [subject, setSubject] = useState (''); const onSubmit = (e) => { e.preventDefault(); const data = new FormData(e.target); console.log(data); fetch("http://127.0.0.1:8000/api/contact/", { method: "POST", body: data, }) .catch((error) => console.log("Request failed", error)); } This is the material UI form which i am using <form onSubmit={onSubmit}> <TextField autoComplete="new-password" id="outlined-basic" label="Full Name" variant="outlined" value={name} onChange={(e) => setName(e.target.value)} required /> <TextField id="outlined-basic" label="Email Address" variant="outlined" autoComplete="new-password" value={email_id} onChange={(e) => setEmail(e.target.value)} required /> <TextareaAutosize className="textbox" aria-label="minimum height" rowsMin={3} placeholder="Subject" value={subject} onChange={(e) => setSubject(e.target.value)} /> <button>Submit</button> </form> While using with material UI form it gives me error that says {"name":["This field is required."],"email_id":["This field is required."],"subject":["This field is required."]} When i use normal html form it works perfectly fine. But when i try to do the same with material-UI form it doesnt work. It will be really helpful if anyone can help. Thanks in advance. -
ImportError: cannot import name 'Blog' from 'blog.models'
Hi Can someone help me to sort out the below issue. Actually, I have created a Port_Folio project and 2 apps with the name of Blog and portfolio. When I import a blog in models it doesn't import and I am getting below error. ImportError: cannot import name 'Blog' from 'blog.models' Actual code is: Import Blog Error-PyCharm Terminal from django.contrib import admin from .models import Blog admin.site.register(Blog) Error: File "C:\Users\zeems\PycharmProjects\DjangoCourse\personal_portfolio-project\blog\admin.py", line 2, in <module> from .models import Blog ImportError: cannot import name 'Blog' from 'blog.models' (C:\Users\zeems\PycharmProjects\DjangoCourse\personal_portfolio-project\blog\models.py) -
Auto refering nesting with Django Rest Framework
I have this model in Django (based on a legacy database): class NationalTest(models.Model): unityId = models.IntegerField(primary_key=True) parentId = models.IntegerField(blank=True) grade = models.FloatField(blank=True) This model stores the grade that a "unity" (a school, a city, a region or a state in our country) received in a national test. unityId is the id of the unity, grade is its grade in the test, and parentId is the id of its upper parent (i.e.: if our unity is a school, parentId the id of the city where the school is located; if it's a city, parentId is the id of the state where the city is located, and so on). For front-end purposes, when I fetch some school's grade, I need also the grade of the city, the state, the region and the whole country (all 5 levels possible). When I fetch a city's grade I need state, region and country's grade too. When I fetch state's grade, just need the two levels above grade. I think that the best way I can solve it is to create a nested serializer based on parentId. I know how to do it when we have a foreign key from another model, but how can I … -
Ajax call not sending any data when added image data using django ajax
I'm trying to send data from a popup form through django template which includes an image also, when tried to access data in console. Data is properly visible. But when ajax function used, no data is received in 'request.POST' in django view. But when image file is removed from AJAX data data is recieved properly HTML code: <div class="form-popup-custom col-lg-12" id="myForm" data-method="POST"> <form enctype="multipart/form-data" action="/action_page.php" class="form-container" method="post"> <div class="header" id="myHeader"> <div class="col-lg-12"> <h5 style="font-size:22px;">Total Amount Selected :</h5> <h5 style="font-size:20px;" id="amount_text">0.0</h5> </div> </div> <input type="hidden" id="amount_text"> <label for="utr" style=" margin-bottom: 2vw; margin-left: 3vw; "><b>Enter UTR number</b></label> <input type="text" id="utr" maxlength="22" minlength="16" placeholder="Enter UTR number" name="UTR" required> <label for="utr"><b>Enter Amount</b></label> <input type="number" id="amt" placeholder="Enter UTR number" name="amt" required> <div class="header" id="myHeader" style=" margin-top: 2vw; "> <label for="enter-amount"><b>Upload UTR slip</b></label> <input type="file" id="slip" placeholder="select file" name="select_file" required> </div> <button type="button" class="btn cancel" onclick="closeForm()">Close</button> </form> </div> </center> <div class="col-lg-12 text-center" style=" text-align: center; "> <input type="submit" id="sbt_btn" onclick="submit()" value="Submit"> </div> Ajax call: function submit() { console.log("isme aa gyaa!!!!!!"); order_ids=Array(); $("input:checkbox[name=_selected_action]:checked").each(function(){ order_ids.push($(this).val()); }); var amount = document.getElementById('amount_text').innerHTML; var utr = document.getElementById("utr").value; var amt = document.getElementById('amt').value; var errorflag = false; files_=Array(); var files = document.getElementById("slip").files[0]; files_.push(files); {#var remark = document.getElementById('request_remark').value;#} if(order_ids.length <= 0){ alert("Please select orders."); … -
Where to define methods unrelated to models in Django project
Is there a convention related to where to define methods unrelated to models in Django? For example, I am developing a dictionary project in which I have a dictionary app as well as a tags app. From one of the views, I needed a method to collect all Tags from multiple Definitions. This method can not be implemented in any of my models.pys. Where should I define such a method? If I need to create a new file, what should I call it? Should it go in the project's folder, the dictionary app's folder, or in the tags app's folders? -
Setting DB index on Redis Django
I am using Redis as my caching server on Heroku, Django. However, when I page loads I get and error: redis.exceptions.ResponseError: invalid DB index My Redis setting is: CACHES = { 'default': { 'BACKEND': "redis_cache.RedisCache", 'LOCATION': os.environ.get('REDISTOGO_URL', 'redis://127.0.0.1:6379'), "OPTIONS": { "CLIENT_CLASS": "redis_cache.client.DefaultClient", } } } Shouldn't the DB index be 0 by default? How can I set the DB index correctly? I have the same settings locally and I do not get this error. Thanks for all the help in advance! -
JavaScript function doesn't work in form loop
JavaScript work only in first iteration, doesn't affect on the field from second iteration. forloop Code Sample {% for i in userlist %} <input id="a{{i.email}}" type="email" value="{{i.email}}"> <input id="b{{i.email}}" type="text" value="{{i.date_of_birth}}"> <input id="c{{i.email}}" type="text" value="{{i.mobile}}"> {% endfor %} Button for disable editing <button onclick="disableProfileEditing()" type="button"> Disable </button> Button for enable editing <button onclick="enableProfileEditing()"> Edit</button> JavaScript function function disableProfileEditing() { var a=document.getElementById("a{{i.email}}"); var b=document.getElementById("b{{i.email}}"); var c=document.getElementById("c{{i.email}}"); document.getElementById(a).disabled = true; document.getElementById(b).disabled = true; document.getElementById(c).disabled = true; } function disableProfileEditing() { var a=document.getElementById("a{{i.email}}"); var b=document.getElementById("b{{i.email}}"); var c=document.getElementById("c{{i.email}}"); document.getElementById(a).disabled = false; document.getElementById(b).disabled = false; document.getElementById(c).disabled = false; } -
Where to place Telegram bot code in my Django app? And how to run it with separate container or a part of Django?
I have Django app and my Telegram bot which interacts with ORM models. Bot can work in two ways: longpooling and webhook. Where to place the code of this bot: In separate Djnago app or in separate folder in the same level as Django place. And how to Run it? As new Docker container with all same dependencies and requirements.txt with Djnago (to have microservices arhitecture but dependencies duplicates) or as a part of django app? How to do this. Please help with best practicies! Thanks -
Discuss Implementation For Marketplace Website In Django
I am building a marketplace website for old mobile phones. I will be building it using django stack. I have figured out the other modules, but am stuck with payment integration for the website.(since I am quite Noob in payments field) I read about PayPal & Stripe integrations in django, but am little doubtful on how to implement these services for my website scenario. Here's the scenario:- Website will have Buyers & Sellers. Buyers - who will buy mobile phones. Sellers - who want to sell mobile phones. Each seller - will have payment details to receive payments (these can be either a paypal ID/ stripe ID) Buyers will need to checkout throut debit cards, credit cards, paypal, stripe etc. (To buy the phones) After a transaction is done, Being a marketplace, we will keep a little service fee in (℅) and handover the rest of amount to seller. Please suggest an approach to implement this scenario. -
explain me this django views
i dont understand the download() part can someone explain me this This is views file in django project def index(request): send_to_index = { 'file' : FieldAdmin.objects.all() } return render(request , 'installer/index2.html' , send_to_index ) def download(request , path): file_path = os.path.join(settings.MEDIA_ROOT , path) if os.path.exists(file_path): with open(file_path , 'rb') as file: response = hr(file.read(),content_type="application/admin_upload") response['Content-Disposition'] = 'inline;filename='+os.path.basename(file_path) return response raise Http404 -
Adding Google allauth on Django live app deployed on Heroku
I am trying to add Google authentication to my live Django app deployed on Heroku. I have added www.example.com and example.com as Site objects and have added them to the list of Sites on the Social Application object in the admin interface on Heroku. However, now that I have both the root(example.com) and subdomain www I cannot add both Site id's in my settings. How can I set the Site id properly in the settings? Since I have now gettings an error: allauth.socialaccount.models.SocialApp.DoesNotExist: SocialApp matching query does not exist. and I get a 500 internal server error when I visit: http://www.example.com/accounts/google/login/ Is the root enough to be added as Site? -
Style is not applied with inlineformset. But works perfectly with simple form
I am able to style the form(view update_order) with widgets in forms. But in inlineformset_factory(create_order) I am facing issues. The widget in not working for inlineformset_factory. https://hastebin.com/mapuliyaxu.cs -
How to create users and groups migrations in Django?
So I've got an API built in Django with Django Rest Framework and I now want to add a role based access control to it. For this I found the django-rest-framework-roles extension. I've got it installed, but I'm not really familiar with the usual authentication system in Django. It says I need to define the groups in the settings as ROLE_GROUPS = [group.name.lower() for group in Group.objects.all()] So I need the Group model and of course also the User model. As far as I understand, these are standard models. However, I don't have any tables in my DB for them. So I need a migration for it, but I'm unsure how I can do that. I guess it should be really easy, but even on the relevant pages in the documentation I don't see any mention on how to add these models to my Django installation. Could anybody enlighten me on this? -
Django form validation for checking uniqueness of record before submitting
I have database table columns like: | FPB_Code | Transaction_Date | Ministry_Code | Created_Date | Created_By | Modified_Date | Modified_By | I have created a form using Django and before submitting the form, I want to check whether records matching from (|FPB_Code | Transaction_Date | Ministry_Code| ) exists or not? Please help. -
ModelChoiceField in Django is not rendered
I'm desperately looking for a solution to following problem: I got a very simple form with one model choice field: from django import forms from django.contrib.auth.models import User class MyForm(forms.Form): my_field = forms.ModelChoiceField(queryset=User.objects.filter(is_superuser=False),widget=forms.Select()) The form is passed to a view and HTML file: <form method = "GET"> {{ form }} <input type = "submit" value = "Submit"> </form> The rendered HTML looks exactly as expected: <form method="GET"> <label for="id_my_field">My field:</label><select name="my_field" required="" id="id_my_field"> <option value="" selected="">---------</option> <option value="2">test1</option> <option value="3">test2</option> </select> <input type="submit" value="Submit"> </form> Still the result in the browser is not as expected: I played around with the widgets attributes for a while, but I still can not figure out why my the options are not rendered. Thanks in advance! -
Python list comprehension Django objects
I am developing a dictionary Django app where Definitions have Tags. I have written this generic function to collect all Tags from a list of Definitions. This is my current working version: def get_tags(definitions): tags = [] for d in definitions: tags += d.tags.all() return tags I was trying to accomplish the same using Python's list comprehension: tags = [] return [tags.extend(d.tags.all()) for d in definitions] This code however does not work yet. What am I missing? Is there an even slicker way to do this in just one line without creating the tags variable, perhaps using yield statement? -
Import Error DJANGO PYTHON - Error Message: 'Unable to import 'rest_framework_simplejwt.tokens'
I have already seen this [link][1] which describes a similar issue but it seems that all the suggested solutions can't help me. This is the error message I get: Unable to import 'rest_framework_simplejwt.tokens' This is the command I use: from rest_framework_simplejwt.tokens import RefreshToken I have also inserted this code in my settings.py file: REST_FRAMEWORK = { 'NON_FIELD_ERRORS_KEY': 'error', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } The documentation says that the Requirements are: Python (3.6, 3.7, 3.8) Django (2.0, 2.1, 2.2, 3.0) Django REST Framework (3.8, 3.9, 3.10) My System when I do pip freeze: argon2-cffi==20.1.0 asgiref==3.2.10 bcrypt==3.2.0 cffi==1.14.2 Django==3.0 djangorestframework==3.10.0 djangorestframework-simplejwt==4.4.0 psycopg2==2.8.6 pycparser==2.20 PyJWT==1.7.1 pytz==2020.1 six==1.15.0 sqlparse==0.3.1 My version of python: Python 3.6.4 :: Anaconda, Inc. Do you have any idea how to fix it? -
Django filter queryset. Need to get all jobs which require at least one skill from list skills
#I have a list of skills skills = p.skill_info #Also in Jobs I have the list of all jobs now I need to get all jobs which contain at least one skill from the skills list. jobs = Job.objects.filter(job_requirements__in=skills) I am doing something like this, what am I doing wrong ? -
Django Admin Related [closed]
Anyone here Django Developer who creates a custom Admin panel from Scratch(does not use Django admin panel). Fully features like sidebar and charts and Some Tables. Please help me with the project.