Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
STATIC FILES PYTHON ANYWHERE
When I run python manage.py collectstatic in the bash console of pythonanywhere I keep getting "python: can't open file 'manage.py': [Errno 2] No such file or directory". But I can clearly see my manage.py file in my code editor, I am a beginner in django and its pretty frustrating. If anyone has any ideas what this can possibly be, I would love your help. Thanks settings.py -
Django Fixtures: Validate before applying
This morning I pushed out an update to our application that added a unique constraint to one of our fields. As part of our deployment, we applied the fixtures and ran across an issue where there was a duplicate in the DB. This created an error in our deployment and gave our users 502 errors for a short time. I am automating our deployment processes and To keep this from happening again, would like to perform some kind of validation on the fixtures before they are applied to the DB. Is there a way to do this in django? Thanks! -
how to add multiple items from the list and add it to text field. and also i want to add item by typing in the input field
<form class="form-horizontal" method="POST" > <div class="form-group col-md-5" > <label for="skill">Skill</label> <input type="text" name="skill" class="form-control"> <select multiple class="form-control" name="taqinput"> <option>css</option> <option>html</option> <option>c++</option> </select> </div> </form> for example if i click on css the css will add into inputfield and also when i write math in the input field it will also be added. -
What is Django Rest API?
I have been learning django from last 1 month,but then i got to see a new term django rest API,so now i am trying to figure out whats the difference between them.Can anyone tell me what's actually the difference between 'django' and 'django rest API', where it is used and should anyone learn it or not? -
How to avoid hard coding URL when submitting form in Django
I have a Django project with a form on the homepage. When the form is submitted, it hard codes a URL which triggers a view function. I am trying to submit that form and trigger the function without hard coding the URL. I have done some research into reverse and reverse_lazy but the actual implementation still makes no sense to me so I am here for help. index.html: <form action= '/add_trans_form' method="POST" id='formALL'> urls.py app_name ='pages' urlpatterns = [ path('', views.index_view, name='index'), path('add_trans_form', views.add_trans_form, name='trans_form') ] views.py def add_trans_form(request): ~do some top secret stuff to my database~ return HttpResponseRedirect(reverse('pages:index')) please note the project name is AIS and the Django app is 'pages' PLEASE help me understand what I am doing wrong... I would like to process the form without changing the url. -
Adding django channels to existing wsgi server causes 400
There is this open source project called okuna-api that I am trying to modify and add chat to for learning purpose. The original okuna runs on wsgi and works fine. Now for chat, I added channels and added asgi to settings, created the asgi.py and routing.py according to channels docs. After doing this and reinstalling the api, the companion app(flutter) starts showing error 400 for all requests, even though the admin panel accessed via browser is working fine. When checking the server logs, it seems to be asgi server only. Asgi should be backward compatible I believe. I don't know what kind of mistake I am making. Is it not possible to run code for wsgi in asgi ? Is there any further modification needed in asgi.py, routing.py and settings ? Or is it possible to run wsgi and asgi simultaneously ? Or is it just a problem with the flutter requests ? I am a newcomer to django, so what is the best approach to the problem ? -
Django Admin - Include field of a model A when adding a record of model B
I'm working on legacy code which is in Django (1.11) I have a model A, with attributes: Model_A: Name (NOT NULL) City (NOT NULL) FieldX (Nullable) - CharField And a model B, with attributes: Model_B: Name (NOT NULL) City (NOT NULL) RelatedField (ForeignKey to an instance of Model_A) Now, When I add a record for Model_A then I may NOT need to fill FieldX. However, When I add a record for Model_B then I'll have to select an instance of Model_A and then if FieldX of that instance is NULL then I have to fill that as well (make it mandatory). The form for Model_A is pretty straight forward. But for Model_B I need a form where: The first instance of Model_A is selected (Dropdown) The input box for FieldX of instance selected in 1 is shown. The rest of the fields are shown (Name, City, FieldY). Can this be done using the admin page? Or will I have to create proper forms and user flow for this? -
Django not loading static files on subpath
Introduction I am using an implementation of Django REST Framework and API with React (create-react-app) and everything works fine if accessed through the React interface via buttons. Also, some links work fine when accessed from the search bar, like the home page (/) and any immediate paths without a trailing slash (E.g. /a or /archive) as you can see here: The Problem Whenever I try to access immediate paths with trailing slashes or any subpath with or without trailing slashes through the browser it provides this error: The Settings Here are some photos of my Django settings: Django Static Files Settings Django Main URLs Django API App URLs Final Comments Thank you for reading this. I hope the photos are helpful and please let me know if you need any other information and I will provide it. Thank you. -
Search bar with Python-Django
i'm trying to build my first Django blog that someone can make an account, search & update posts and now i want to add a search bar so someone can find others by profile name. But i don't know how to make it exactly, i try to find something on google but nothing help me. i try this: ( on the base.html ) <form type="get" action="/other/path/" style="margin: 0"> <input id="search_box" type="text" name="search_box" placeholder="Search..." > <button id="search_submit" type="submit" >Submit</button> ( on the views.py ) @login_required def search_bar(request): if request.method == 'GET': search_query = request.GET.get('search_box', None) ( on the urls.py ) path('', UserPostListView.as_view() , name='search'), -
Django: is it possible to use data/context from a django rest framework APIview inside HTML?
I have this class view to display some chart.js on my homepage: class chartData(APIView): authentication_classes = [] permission_classes = [] renderer_classes = [TemplateHTMLRenderer] template_name = 'index.html' def get(self, request, format=None): ... data = { "data1": data1, "data2": data2, ... } return Response(data) My function view for the homepage is this: def index(request): return render(request, 'index.html') My question is: Is it possible to use the data from the class chartData(APIView) and display it inside HTML like this --> {{data1}} -
Is there a simple way to design document with Reportlab?
I`ve got an invoice html document designed and looking like I want. I would like to use reportlab to generate a pdf. Each time, I am making some changes to the canvas in my view to match my html document, I need to reload the app and it seems to takes a while to develop this pdf. Is there a quicker to test or create the canvas? Many thanks, -
How to scale Django RQ workers that can read from source directory & be able to write to database?
How to "Scale" RQ workers? I have architecture like this uwsgi/django (machine 1) <=> RQ server (machine 1) <=> RQ worker 1...n (machine 1) Problem is.. RQ workers are eating up all the CPU so the Django/uwsgi is almost unresponsive during high load So I want to do something liket his uwsgi/django (machine 1) <=> RQ server (machine 1) -> RQ worker 1 (machine 2) -> RQ worker 2 (machine 3) -> ... -> RQ worker n (machine n-1) Problem is, I'm using Django RQ (django wrapper for RQ).. and the RQ workers are spawned from a specific directory and need to be able to write to database If I split up the RQ workers into other machines, i need the workers to be able to read from django source directory be able to write to Django App database #2 can be solved with microservice.. however I'm a bit stuck I can do something like SSHFS but i am not 100% certain if this is a "good" design in terms of scalability, security, and of course, complexity ( i dont' want to keep adding more monitors / software stack). Of course, I can just have a script that pulls down … -
I keep getting an error when I deploy my app on heroku
I followed a tutorial on how to deploy apps on heroku After deploying I opened the page and saw application error, I checked my logs 2020-07-29T19:40:59.398818+00:00 heroku[run.1760]: State changed from starting to up 2020-07-29T19:40:59.543326+00:00 heroku[run.1760]: Awaiting client 2020-07-29T19:40:59.573857+00:00 heroku[run.1760]: Starting process with command python manage.py migrate 2020-07-29T19:41:06.780115+00:00 heroku[run.1760]: Process exited with status 0 2020-07-29T19:41:06.825218+00:00 heroku[run.1760]: State changed from up to complete 2020-07-29T19:41:59.632795+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=fruit- wurld.herokuapp.com request_id=59cd7c94-4b9d-4d31-b0bb-e6f03f235c7a fwd="129.205.124.156" dyno= connect= service= status=503 bytes = protocol=https 2020-07-29T19:42:00.036677+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=fruit-wurld.herokuapp.com request_id=44d555d7-ce8a-4aa8-8933-35b72db38d61 fwd="129.205.124.156" dyno= connect= service= statu s=503 bytes= protocol=https -
Posting multiple images and data to database via django
I would like to post multiple pics from my vue.js form (frontend) into my database via django (backend). I'm using this solution for my vue script, but I additionally post picture id, which is foreign key to another table. I've already tried with File Storage API, REST APIView unsuccessfully. Here is my model: class gallery(models.Model): idpic = models.ForeignKey(News, on_delete=models.CASCADE) photo = models.ImageField(upload_to='img', null=True) and my vue script: if(this.disabled2==true){ const id = this.info[0].id + 1; for( var i = 0; i < this.file2.length; i++ ){ let img = this.file2[i]; console.log(obraz); formData2.append('idpic[' + i + ']', id); formData3.append('photo[' + i + ']', img, id + '_' + i + '.jpg'); } } axios.post(link2, formData2, { headers: { 'Content-Type': 'multipart/form-data'} }) .then(res => { console.log(res.data);}) .catch(err => console.log(err)) Below are my 'views.py attempts' #this one doesn't work from the beginning, because body unicode tries to decode file def Gallery(request): if request.method == 'POST': body_unicode = request.body.decode('utf-8') body_data = json.loads(body_unicode) idpic_front = body_data['idpic'] pics = request.FILES['photo'] fs = FileSystemStorage(location="path") for p in pics: insert_gallery = gallery.objects.create(idpic=idpic_front, photo='img'+pics.name) fs.save(pics.name, pics) result = list(insert_gallery) return JsonResponse(fs, rezultat) #this one uploads only the last selected picture class GalleryView(APIView): parser_classes = (MultiPartParser, FormParser) def get(self, request, *args, **kwargs): … -
AttributeError at /stories/6/segnala-commento/14/ 'NoneType' object has no attribute 'storia' Django
How i fix this error??? views.py @login_required def segnalaCommento(request, id, pk): commento = get_object_or_404(Commento, id=commento.storia.id, pk=pk) commento.segnala += 1 commento.save() return HttpResponseRedirect(commento.storia.get_absolute_url()) HTML Page <a href="{% url 'segnala-commento' id=commento.storia.id pk=commento.pk %}"><p class="badge badge-danger mb-0">Segnala</p></a> urls.py path('<int:id>/segnala-commento/<int:pk>/', segnalaCommento, name="segnala-commento"), Thank you -
Problem running celery: No module named 'transport'
I'm using Celery in Django project but when I try to run celery worker -A my_app -l info or celery beat -A my_app -l info, the following error is triggered: celery worker -A my_app -l info return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'transport' celery beat -A my_app -l info [2020-07-29 14:14:07,506: WARNING/MainProcess] ModuleNotFoundError [2020-07-29 14:14:07,506: WARNING/MainProcess] : [2020-07-29 14:14:07,506: WARNING/MainProcess] No module named 'transport' I don't know where this mistake came from. Celery configuration CELERY_TIMEZONE = TIME_ZONE CELERY_BROKER_URL = redis://localhost:6379 CELERY_RESULT_BACKEND = CELERY_BROKER_URL CELERY_ACCEPT_CONTENT = ["json"] CELERY_TASK_SERIALIZER = "json" CELERY_RESULT_SERIALIZER = "json" CELERY_TASK_TIME_LIMIT = 5 * 60 CELERY_TASK_SOFT_TIME_LIMIT = 60 Celery set up from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") app = Celery("my_app_name") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() current task from celery import shared_task @shared_task def send_message_with_attachments(message) -> None: """Send mails or Whatsapps with attachments.""" send_mail( subject=message.subject, message=message.content, recipient_list=message.recipient_mails, ) Task execution I execute the task in admin @admin.register(Message) class MessageAdmin(admin.ModelAdmin): def save_related(self, request: Any, form: Any, formsets: Any, change: bool) -> None: super().save_related(request, form, formsets, change) send_message_with_attachments.delay(form) Environment … -
What is the difference between DTL and jinja2 in Django?
I read many Articles but the answer was not satisfying. Well I have been using DTL and I'm good satisfied with it. Jinja is similar library which is cool too. But being Django user when we can use jinja2 -
Pandas df column values = NaN, Django (django-pandas)
I'm using django pandas(https://github.com/chrisdev/django-pandas/), to grab data from a django model into a pandas dataframe. I first create a df with the indexes, and then try to add columns to it. My function: def market_value(self, ticker_list): date_yesterday = date.today() - timedelta(days=1) date_today = date.today() market_value_list = [] first_ticker = ticker_list[0] first_data = Ticker_historic_prices.objects.filter(ticker=first_ticker) first_df = read_frame(first_data, fieldnames=['close']) df_date = read_frame(first_data, fieldnames=['date']) df = pd.DataFrame(index=df_date['date']) for ticker in ticker_list: modelToDf = Ticker_historic_prices.objects.filter(ticker=ticker) df[ticker] = read_frame(modelToDf, fieldnames=['close']) print(df) But my output looks like this: YAR.OL NHY.OL TSLA MSFT STB.OL DNB.OL SBO.OL date 2004-03-24 NaN NaN NaN NaN NaN NaN NaN 2004-03-25 NaN NaN NaN NaN NaN NaN NaN 2004-03-26 NaN NaN NaN NaN NaN NaN NaN 2004-03-29 NaN NaN NaN NaN NaN NaN NaN 2004-03-30 NaN NaN NaN NaN NaN NaN NaN ... ... ... ... ... ... ... ... 2020-07-15 NaN NaN NaN NaN NaN NaN NaN 2020-07-16 NaN NaN NaN NaN NaN NaN NaN 2020-07-17 NaN NaN NaN NaN NaN NaN NaN 2020-07-21 NaN NaN NaN NaN NaN NaN NaN 2020-07-22 NaN NaN NaN NaN NaN NaN NaN The date part is correct, but why do I get NaN values? I have tested, by running the first_df I do get … -
Django QuerySet aggregate based on field value
My model is as follows: class AssetIdentifications(models.Model): id = models.BigIntegerField(primary_key=True, db_index=True, editable=False, null=False) entity = models.ForeignKey( "Entity", db_constraint=False, null=False, ) asset = models.ForeignKey( "Asset", db_constraint=False, null=False ) type = models.CharField( max_length=32, null=False, ) vendor = models.CharField( max_length=64, null=False ) software = models.CharField( max_length=64, null=False ) version = models.CharField( max_length=64, null=False ) I want to get a queryset that is grouped based on unique values of vendor. The result should look something like this: {"vendor1": [\<list of AssetIdentifications\>], "vendor2": [\<list of AssetIdentifications\>] ...} Is this possible with a group_by or aggregate function (I haven't found something like this in the docs)? Or would I have to iterate through the queryset I obtain just through filtering like AssetIdentifications.objects.filter(entity=e) -
Django: Updating through a post() method a CBV object with FormMixin and ListView
I'm trying to update an specific value of the objects shown trough the ListView. I found a possible solution using FormMixin, but when the input is done using the <select> tag, instead of updating the object value trough the form, a new object is created. models.py: class Quote(models.Model): STATUS = ( ('E', 'Entregada'), ('R', 'Revaluada'), ('C', 'Confirmada'), ('A', 'Anulada'), ) client_name = models.CharField(max_length=40) client_last_name = models.CharField(max_length=40) status = models.CharField(max_length=1, default='', choices=STATUS, blank=True, null=True) forms.py: class QuoteChangeStatusForm(forms.ModelForm): class Meta: model = Quote fields = ['status'] widgets = { 'status': forms.Select( attrs = { 'class': 'form-control-sm', 'onChange':'this.form.submit();' } ) } views.py: class QuoteListView(FormMixin, ListView): model = Quote template_name = 'quoter/quote_list.html' form_class = QuoteChangeStatusForm success_url = reverse_lazy('quoter:quote-list') context_object_name = 'quotes' queryset = Quote.objects.all() def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): form.save(commit=True) return self.form_valid(form, **kwargs) else: return self.form_invalid(form, **kwargs) quote_list.html: <form method="POST"> {% csrf_token %} <h5>Status: <br>{{ form.status }}</h5> </form> Thanks in advance! -
In the Django Admin, the ManyToMany second box doesn't appear for some of my models. How can I display it back?
I'm making an app with Django 3.0.8 and I'm customizing the Django admin panel in order to make it more user-friendly for the administrators. But the problem is that some (almost all) of my ManyToMany fields in my models are not displaying correctly. Usually, you should have to boxes. On on the left (or above if your screen isn't large enough) where you can select the related objects, and one on the right (or bellow) of the first one, containing the objects already selected. You can use the arrows between to boxes to add or remove one or more objects from one box to the other. The problem is that in my case, the right/bottom box and the arrows disappeared. i cannot see which objects are related to my current object and therefore I cannot remove some of them from the relationship, which is problematic. I post this because I already had this with a couples of Django apps. -
Is there any way to get reversed nested serializers in django rest framework?
Suppose i have two models: class Region(models.Model): region_name = models.CharField( max_length=50, null=False, blank=False, unique=True, verbose_name="Region Name" ) def __str__(self): return self.region_name class Meta: verbose_name_plural = "Regions" class Country(models.Model): region_id = models.ForeignKey( Region, null=True, blank=True, on_delete=models.CASCADE, verbose_name="Region id", ) country_name = models.CharField( max_length=50, unique=True, null=False, blank=False, verbose_name="Country Name" ) def __str__(self): return self.country_name class Meta: verbose_name_plural = "Countries" Now, when i access the country model through Djnago REST Framework, as /api/countries I get country_name and region_id for example [ { "id": 1, "country_name":"Taiwan", "region_id": 1 }, ... ... ] Is there any way to get the result like: [ { "id": 1, "country_name":"Taiwan", "region_id": { id: 1, region_name: "Asia", } }, ... ... ] I have tried nested serializer example as on the DRF website, but it returns a list of countries if we get the regions api. like: [ { "id": 1, "region_name":"Asia", "countries": [ "Taiwan", "Japan", "Vietnam", ... ] }, ... ... ] I need to know the region name of the country in one api get request. Right now i am using 2 requests. One to get country, and then get region name from region id. -
mysql client not installed
i want install "mysql client" package but i have error. the error is : Defaulting to user installation because normal site-packages is not writeable Collecting mysqlclient Using cached mysqlclient-2.0.1.tar.gz (87 kB) Using legacy setup.py install for mysqlclient, since package 'wheel' is not installed. Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'c:\program files (x86)\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\HaMiD\\AppData\\Local\\Temp\\pip-install-c4vd2bfk\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\HaMiD\\AppData\\Local\\Temp\\pip-install-c4vd2bfk\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\HaMiD\AppData\Local\Temp\pip-record-3c2b32j1\install-record.txt' --single-version-externally-managed --user --prefix= --compile --install-headers 'C:\Users\HaMiD\AppData\Roaming\Python\Python38\Include\mysqlclient' cwd: C:\Users\HaMiD\AppData\Local\Temp\pip-install-c4vd2bfk\mysqlclient\ Complete output (29 lines): running install running build running build_py creating build creating build\lib.win32-3.8 creating build\lib.win32-3.8\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.8\MySQLdb creating build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.8\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension creating build\temp.win32-3.8 creating build\temp.win32-3.8\Release creating build\temp.win32-3.8\Release\MySQLdb C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.23.28105\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(2,0,1,'final',0) -D__version__=2.0.1 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include\mariadb" "-Ic:\program files (x86)\python38-32\include" "-Ic:\program files (x86)\python38-32\include" "-IC:\Program … -
ImportError at / Module "cart.context" does not define a "cart_context" attribute/class
Im trying to create a django cart page. im having an issue adding products/plans to a cart and im also having an issue on showing a quantity of items in the cart. Ive made a context.py to try add to the cart but im not too sure what im doing wrong. im getting an error message ImportError at / Module "cart.context" does not define a "cart_context" attribute/class Heres my context.py file from django.shortcuts import get_object_or_404 from plans.models import Plans def cart_contents(request): """ Enables the cart contents to be shown when rendering any page on the site. """ cart = request.session.get('cart', {}) cart_items = [] total = 0 product_count = 0 for (id, quantity) in cart.items(): product = get_object_or_404(Product, pk=id) total += quantity * product.price product_count += quantity cart_items.append({'id': id, 'quantity': quantity, 'product': product}) return {'cart_items': cart_items, 'total': total, 'product_count': product_count} Heres my cart views from django.shortcuts import render, redirect, reverse # Create your views here. def view_cart(request): """ A view that renders the cart page """ return render(request, 'cart/cart.html') def add_to_cart(request, item_id): """ Add plan to shopping cart """ cart = request.session.get('cart', {}) cart[item_id] = cart.get(item_id, 1) request.session['cart'] = cart return redirect(reverse('plans')) Add here is my navbar cart link, where … -
how to pass instance post image in email template in django?
i need to send post update through email to the users with the instance post image, but i dont know how to pass the instance post image to the email template. signals.py def sendUpdateMail(sender,created,instance,**kwargs): if created: if instance.status == 'Published': subject=instance.postTitle message=Truncator(instance.postContent).words(30) from_email=settings.EMAIL_HOST_USER email=list(NewsletterUser.objects.values('email')) d={'postContent':instance.postContent,'title':subject} recepients=[] html_templatey=get_template("blog/postUpdateMail.html").render(d) #recepients=[p.email for p in NewsletterUser.objects.all()] for p in NewsletterUser.objects.all(): recepients.append(p.email) email=EmailMultiAlternatives(subject,'',from_email,recepients) email.attach_alternative(html_templatey,'text/html') email.send()