Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create ForeignKey in Django that connects only part of foreign Queryset?
I'm creating backend for Kiosks and each Kiosk model has Location model connected. But some locations have flag 'disabled'. I'm trying to remove this Locations from dropdown menu in Django Admin -> Kiosk so user couldn't choose it while creating/updating Kiosk instance. I see two potential ways to solve it: Edit Django admin page for Kiosk so in dropdown menu he can see only filtered results Create proxy model with filtered results that would be connected to Kiosk I would be happy to hear your suggestions, criticism Let's suggest that models look like this: class Location(models.Model): '''Location of Kiosks''' class Meta: verbose_name = "Location" verbose_name_plural = "Locations" def __str__(self): return self.name name = models.CharField('Name', max_length=60) description = models.TextField('Description') enabled = models.BooleanField('Location enabled', default=True) class Kiosk(models.Model): '''Kiosk unit''' description = models.TextField('Description') uuid = models.CharField('Kiosk ID', unique=True, max_length=30) location = models.ForeignKey(to=Location, on_delete=models.CASCADE) -
got an unexpected keyword argument 'id'
I'm trying to do a query when the object has the status = 'Opened'. And display in a table where I will have a button to give a solution for my form and change status='Pending'. But when I click in the button I get this error. What I'd like to do for really is display was a form for each data, but when I do a for loop for each one form my data insnt show url: path('manutencao_os_status/<int:id>', views.manutencao_ordem_de_servico, name='manutencao_os_status'), path('manutencao_ordem_de_servico/', views.manutencao_ordem_de_servico, name='manutencao_ordem_de_servico'), views.py def manutencao_ordem_de_servico(request): ordem_servico = OrdemServico.objects.filter(status='Aberto').order_by('id') form = FormOrdemServico(ordem_servico) if request.method != 'POST': return render(request, 'ordemservico/manutencao_ordem_de_servico.html', { 'form': form, 'ordem_servico': ordem_servico }) form = FormOrdemServico(request.POST, ordem_servico) if not form.is_valid(): return render(request, 'ordemservico/manutencao_ordem_de_servico.html', { 'form': form, 'ordem_servico': ordem_servico }) ordem_servico.save() return redirect('ordemservico:manutencao_ordem_de_servico') def manutencao_os_status(request, id): ordem_servico = OrdemServico.objects.get(pk=id) ordem_servico.status = 'Em Aprovação' ordem_servico.save() return redirect('ordemservico:manutencao_os_status') html: {%extends 'base.html' %} {%block conteudo %} <h1>Ordens de Serviço</h1> <section class="content"> <div class="container-fluid"> <div class="row"> <div class="card card-primary"> <div class="table table-bordered"> <table class="table table-bordered"> <thead> <tr> <td>Condition:</td> <td>ID:</td> <td>Name:</td> <td>Status:</td> <td>Solution:</td> </tr> </thead> <tbody> {% for os in ordem_servico %} <tr> <td> <a href="{% url 'ordemservico:manutencao_os_status' os.id %}" class="btn btn-success">Aprovar</a> </td> <td>{{os.id}}</td> <td><a href="{% url 'ordemservico:editar_ordem_de_servico' os.id %}"> {{os.name}}</a></td> <td>{{os.status}}</td> <td>{{os.solution}}</td> </tr> … -
How to add a new record as a guest
I am a beginner in Django and I am very need your help. Part of code: models.py from django.contrib.auth.models import User class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) department = models.CharField(max_length=200) def __str__(self): return self.user.username class hardware(models.Model): hostname = socket.gethostname() login_username = getpass.getuser() user = User.username hardware_name = models.CharField(max_length=20) order_no = models.CharField(max_length=10) price = models.DecimalField(max_digits=5,decimal_places=2) confirm = models.BooleanField(default=False) login_user = models.ForeignKey(Author, on_delete=models.CASCADE) computer_login_user = models.CharField(max_length=10,default=login_username) computer = models.CharField(max_length=30,default=hostname) def __str__(self): return self.order_no views.py def get_author(user): qs = Author.objects.filter(user=user) if qs.exists(): return qs[0] return None def new_record(request): form = OrderForm(request.POST or None, request.FILES or None) if form.is_valid(): author = get_author(request.user) form.instance.login_user = author form.save() return redirect(all_records) context = { 'form': form } return render(request, 'orders/form.html', context) I will try to explain my problem briefly. Computers are in public places (productions) and anyone can add new record. That why in the table is info about hostname, who is login on computer and login user. So it works well when the user is logged in to the system, but there is a problem when a new record tries to add an unlogged user (guest). Is an error "'AnonymousUser' object is not iterable". I know that request.user is empty now. Ok, Now questions... How to … -
Do I need to change my normal Django code when introducing Django Channels?
Hello I am a beginner in the python world, so I am still trying to understand the care when working with ASGI. I read some tutorials and documentation, as well as watched some videos on youtube. However, I was unsure on some points. I have a small backend application using Django + Django Rest Framework. My code is very trivial, composed of the most common concepts in the framework: views, serializers, models, urls, etc. In addition, I use a relational database. My environment is this: Python 3.8 Django 3 Django Rest Framework 3.11 Now, I need to add support for WebSockets and I did the basic configuration described in the Django Channels tutorial: I installed Django Channels 2.4.0 (Daphene 2.5.0) Added 'channels' to INSTALLED_APPS I created a routing.py file with an empty ProtocolTypeRouter I added ASGI_APPLICATION to my settings.py I configured the asgi.py file to use channels At the moment, I have not configured any channel layers At the moment, I haven't created any WebSocket endpoint After these configurations the runserver is using an ASGI development server and apparently my REST endpoints are all working. Some questions: Considering that all my code is synchronous, wouldn't it be necessary to make … -
Running a python file other than views.py in django
I am running a django project and I want to divide up my python code into separate files. At the moment I am running my functions from views.py. In my views.py I have a plot function. I have taken this plotting code and I have created python file called plotting.py which has this plot function in it. this plotting file lives in the same folder as my views.py My problem is accessing this plotting.py file. I am trying to access it through from the urls.py by path('plot', plotting.plot),. it is not working. Or do I have to link back to a function in views.pyand from tat function go toplotting.py`? -
AssertionError: False is not true when testing ModelForm in Django
I am trying to test order form and I got the error False is not true when testing a ModelForm. The output is pretty hard to debug and find the answer, Since the pattern I've used is same for all of the other forms I already tested but with Ok outcome. Here is the code: test_form.py from django.test import TestCase from checkout.forms import MakePaymentForm, OrderForm from django import forms def test_order_form_form(self): #test if the form is valid form = OrderForm(data={ 'full_name':'john test testing', 'phone_number': '12345678', 'country':'Brazil', 'postcode': '98u887y776', 'town_or_cit':'Guarulhos', 'street_address1':'Av Jetulio Vargas', 'street_address2':'Mooca', 'county':'Praca da republica' }) print(form.errors) self.assertTrue(form.is_valid()) forms.py from django import forms from .models import Order lass OrderForm(forms.ModelForm): class Meta: model = Order fields = ( 'full_name', 'phone_number', 'country', 'postcode', 'town_or_city', 'street_address1', 'street_address2', 'county' ) models.py class Order(models.Model): full_name = models.CharField(max_length=50, blank=False) phone_number = models.CharField(max_length=20, blank=False) country = models.CharField(max_length=40, blank=False) postcode = models.CharField(max_length=20, blank=True) town_or_city = models.CharField(max_length=40, blank=False) street_address1 = models.CharField(max_length=40, blank=False) #street_address2 not required so customers can leave it blank street_address2 = models.CharField(max_length=40, blank=True) county = models.CharField(max_length=40, blank=False) date = models.DateField() def __str__(self): """The {0}-{1}-{2} is the order in which the id(0), date(1) and full_name(2) will be displayed """ return "{0}-{1}-{2}".format(self.id, self.date, self.full_name) -
webpack-bundle-tracker not creating webpack-stats.json?
I am trying to use Vue and Django together as described in this article. Everything seems to be working except for the webpack-bundle-tracker. I'm pretty sure that webpack-bundle-tracker is not even installed as this happens when I run yarn add webpack-bundle-tracker --dev: yarn add v1.22.4 info No lockfile found. [1/4] 🔍 Resolving packages... error An unexpected error occurred: "https://registry.yarnpkg.com/core-js: self signed certificate in certificate chain". However when I run npm install --save-dev webpack-bundle-tracker it seems to work? but nothing really changes and no webpack-stats.json file is generated. The other thing could be the django-webpack-loader, as when I ran pip install django-webpack-loader gives off a bunch of permissions errors, but it worked when I ran pip install django-webpack-loader --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --trusted-host pypi.org. The error django gives me when I try to open my vue/django test page: Error reading /Users/$ME/Dev/digiproj/vue_frontend/webpack-stats.json. Are you sure webpack has generated the file and the path is correct? Just not sure where to go from here and would greatly appreciate any help. -
model_to_dict() with a @property field is not being included
I am trying to include a field that is a property in the model_to_dict fields list. class Person(models.Model): thumbnail = models.ImageField(upload_to='bla...') ...snipped... @property def thumbnail_url(self): return self.thumbnail.url def toJSON(self): return model_to_dict(self, fields=[..., 'thumbnail_url',...]) When I call Person.toJSON() it does not include thumbnail_url field. What is wrong? Thank you. -
order_by with multiple criteria causes distinct to misbehave
class Titlecomplaint(models.Model): title= models.ForeignKey("titles.title", on_delete= models.CASCADE) user= models.ForeignKey("auth.user", on_delete= models.CASCADE) content = models.TextField(max_length=250,null=True,blank=True) created_date = models.DateTimeField(auto_now_add=True) From the model above I need to get only one copy of every title, while sorting titles by the amount of title. When the amount is equal, I want to sort by "created_date". the_titles= Titleispit.objects.values_list('title', flat=True).distinct().annotate(cnt=Count("title")).order_by("-cnt") But when I add a second order_by criteria distinct() stops working and returns all the model instances without removing duplicates. -
Common architectures for distributed Dockerized web app and API calls to other Docker containers
My web app consists of several coponents: A Django web app in a docker container Several docker containers that are frequently called by the Django web app (some more, some less frequently) A database (postgresql) to which the Django web app will connect to I want to deploy such a web app on AWS, such that we have very low latency in many geographic regions (even with heavy load in some regions, some regions with less heavy load) and also the API call latency should give you answers in real-time (a few ms latency even if these Docker containers are frequently accessed). Is that possible on AWS and if so, what wound be common, fast, reliable, and distributed architectures to use for making this web app fulfil all the requirements? -
how can I fix the duplication between two apps in Django?
I have trouble when I installed allauth package. I followed up the lesson that tells me to put allauth and some app that related to it into installed_apps in settings.py like you show below in the code. when I run the command migrate I face that error: Application labels aren't unique, duplicates: account I found the answer and that because of conflicting allauth.account with account.apps.AccountConfig then I did see that I have to modify my app at apps.py file by adding a label and I did that now I got this error: Migration my_account.0010_auto_20200210_2055 dependencies reference nonexistent parent node ('account', '0009_auto_20200210_2004') I have no idea How can I skip this issue? apps.py from django.apps import AppConfig class AccountConfig(AppConfig): name = 'account' label = 'my_account' settings.py 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__))) # 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 = '$mnlm^=iqx1*#vk_nqx=1492!=)@&ng1q9r9-+(_(c^!%*$sf2' # 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.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'index.apps.IndexConfig', 'account.apps.AccountConfig', 'community.apps.CommunityConfig', 'allauth', 'allauth.account', … -
I would like to know if I can connect my existing postgresql to my heroku app
I have scoured the web for this. All I find is how to setup a fresh Heroku app with a fresh PostgreSQL server. By fresh I mean nothing added. Before I start over, I just want to know if its possible to hook up a completed PostgreSQL database to a completed Heroku app. Or do I need to connect the two in the beginning before I create anything. -
Execute Python Commands on Vps Server with Get Request
On My server, i have installed spleeter which is a python app. I am able to successfully call the spleeter commands in my terminal to execute my required commands. I want to be able to execute those terminal commands with an http get request. Basically, i have an android app thats supposed to make a Get request to my vps server which executes the spleeter commands and returns the response. Please how can i create the Get endpoint. I need pointer please. -
ValueError: Missing staticfiles manifest entry even after collectstatic
I'm getting server errors because django can't find one of my static files even though I can see it in the folder: ValueError: Missing staticfiles manifest entry for 'staticfiles\assets\img\icons\theme\communication\adress-book-2.svg' I see the file sitting in this folder right here in both static and staticfiles: static\assets\img\icons\theme\communication\ file path in template: {% load static %} <img src="{% static 'assets\img\icons\theme\communication\adress-book-2.svg' %}" alt="Confirmation Icon" class="icon bg-primary" data-inject-svg="data-inject-svg"> Running collectstatic doesn't have any effect. Any ideas? Thanks! EDIT: Forgot to add settings.py static settings: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) DEBUG_PROPAGATE_EXCEPTIONS = True STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' -
Thread is blocked in django - Python
the last 4 hours I have been trying to understand threading with django. Nothing seems to work. I want to let the website run in the foreground and let the backend communicate with some other devices on a thread. I want the thread to start at the startup of the website but the program is stuck when I call the thread until the thread comes to an end. Do you know a way to fix it? Please I need help. The urls.py file def add(x, y): i=0 while i < 100000000: x += y i += 1 def postpone(function): t = threading.Thread(target=function, args=(1,)) t.setDaemon(True) t.start() return 0 print("Before thread") postpone(add(4,4)) print("After thread") The server will not start until the while loop is finished. Thanks for reading, I hope someone knows an answer. -
How to get django model field into html template?
First time posting on here and new to Django, sorry in advance. Im trying to plug the name field from my model into my html template, which I will then convert to a pdf. Everything involving the html to pdf conversion is working, I just cant seem to get the name field from my model to work into the html_template when it renders. Ive tried adding 'name' : name into the context_dict within the render_to_pdf view, and that did not work. I think I am likely missing something in my view. pdf_template.html {% block content %} <div class="container"> <div class="row"> <p> **{{name}}** </p> </div> {% endblock %} models.py class User(models.Model): username = models.CharField(max_length = 20, primary_key=True) name = models.CharField(max_length = 20) def __str__(self): return self.name views.py def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None -
Gunicorn gevent workers vs Uvicorn ASGI
I'm currently developing a service in Django which makes use of a slow external API (takes about 10s to get a response), which means the connections to my server are kept open waiting for the external API to respond, and occupying worker time/resources. I know I can use gunicorn's thread or gevent workers to add concurrency, but can't seem to grasp the exact difference between using gunicorn with gevent workers and uvicorn (or any other server) with the asgi interface. What would be the criteria for using one over the other? Django still doesn't fully support async/await views. Would it be better if I just stick with gevent workers? -
Aplication Error, Code=H14 "No web processes running", path="/favicon.ico"
Heroku returns me this message when i try open the app Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail the error is: 2020-06-23T20: 04: 27.882267 + 00: 00 heroku [router]: at=error code=H14 desc="No se están ejecutando procesos web" método=GET ruta="/favicon.ico" host =proyectojoao.herokuapp.com request_id=852edcba-a708-41ec-90e4-306366cf68d3 fwd="104.33. 31.5 " dyno= connect= service= estatus=503 bytes= protocol=https I tried scale dynos, but this return: Couldn't find that process type (web) And i have the Procfile archive in the root of my project whit: web: gunicorn blog.wsgi --log-file - -
Django: I'm stuck with the admin register when dealing with foreign keys and many to many fields inside that foreign key model
I have a model Workout, WorkoutDay and Exercise. A workout can have multiple workoutdays. A workoutday consists of multiple exercises. Each exercise can be added to multiple workoutdays. Between the relation of workoutday and exercise, there needs to be extra fields included (like amount_required). What I would like to have in the admin view is: An admin user can add a new workout (with some fields), can add multiple workoutdays, adding multiple exercises to 1 workoutday. I already tried to make Workoutday an inline adminModel. That works, but I cannot have exercises included in this way. To visualise it more: Workout 1: Workoutday1: Exercise1 - amount_required: 10 Exercise2 - amount_required: 50 Workoutday2: Exercise1 - amount_required: 12 Workoutday3: Exercise2 - amount_required: 20 Exercise3 - amount_required: 20 Can somebody help me please? -
i am having the error: ''TemplateDoesNotExist at /seller2/'' while i open the page. I have my all files below. Could anyone just help me solve it?
I have been trying to get rid of the : ''TemplateDoesNotExist at /seller2/'' while adding images to the database. I have created url(seller2) which calls the method from views.py that is Seller2. In this method I have taken form = ProductForm and return the html file. The ProductForm has been importing from forms.py which creates a form for product and its details. <urls.py> `from django.conf.urls import url from . import views from . import views as user_views from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$',views.Front,name='Front'), url(r'^Register/$',user_views.Register,name='Register'), url(r'^signup_form_submitted/$',views.signup_form_submitted, name='signup_form_submitted'), url(r'^Login$',auth_views.LoginView.as_view(template_name='netauction/LogIn.html'), name='Login'), url(r'^Logout/',auth_views.LogoutView.as_view(template_name='netauction/LogOut.html'), name='Logout'), url(r'^Home/',views.Home, name='Home'), url(r'^Automobiles/',views.Automobiles, name='Automobiles'), url(r'^Furnitures/',views.Furnitures, name='Furnitures'), url(r'^Musical_Instruments/',views.Musical_Instruments, name='Musical_Instruments'), url(r'^Home&Garden/',views.Home_Garden, name='Home_Garden'), url(r'^Antiques/',views.Antiques, name='Antiques'), url(r'^Fashion/',views.Fashion, name='Fashion'), url(r'^Sports/',views.Sports, name='Sports'), url(r'^Collection&Arts/',views.Collection_Arts, name='Collection_Arts'), url(r'^Seller/',views.Seller_Form,name='Seller_Form'), url(r'Seller/form_submitted/',views.seller_form_submitted, name='seller_form_submitted'), url(r'^seller2/',views.Seller2, name='Seller2') ] if settings.DEBUG:urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)` <views.py> `from django.shortcuts import render, redirect from .models import Users from pip._internal import req from django.core.files.storage import FileSystemStorage from .forms import ProductForm def Seller2(request): form = ProductForm() return render(request,'seller2.html',{ 'form': form})` <models.py> `from django.db import models class Products_Details(models.Model): seller = models.ForeignKey(Sellers_Details, on_delete=models.CASCADE) product_name = models.CharField(max_length = 100) product_category = models.CharField(max_length = 100) product_features = models.CharField(max_length = 400) product_images = models.FileField(upload_to='Product_Images') product_starting_price = models.DecimalField(max_digits=10, decimal_places=2) product_current_price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): … -
Integrate Django with Jw player + Cloud front
Hi , I am working on Django Project , and i've integrated Django with aws S3 and Cloudfront , but i need to prevent the videos from Download using Jw player , My question here , how to integrate Jw player with Cloudfront ?? and if there any another way to prevent Download Videos Please Advice me . Thanks for all . -
Migrating dajngo site sql ImageField 404
I recently created a small site to learn django but after migrating it from my laptop to my Raspberry Pi I have an issue with the ImageField attribute. Basically everything migrated properly (the site renders and the db contains all the correct info) but the ImageField no longer works. Even when I try adding a new ImageField model I get a 404. I wonder if it has anything to do with the STATIC_URL and MEDIA_URL constants? Honestly I have a really hard time understanding how to set up the ImageField upload_to argument STATIC_URL and MEDIA_URL to get the images to load properly. I got it working on my pc without really understanding how (I read 4 different contradictory tutorials). If anyone can explain this to me once and for all I would be very grateful. I don't often post on stack overflow so let me know how I can edit my post to be clearer. What I've done: Clone site using git Save Postgres to disk using Admin (data + schemas) Load database using Postgres commands on Raspberry Pi Config in settings.py: STATIC_URL = "/static/" #MEDIA_URL = "D:/Personal/django-robin-maillot-website/personalsite/" (before migrating to pi) MEDIA_URL = "/home/pi/django-robin-maillot-website/personalsite/" STATICFILES_DIRS = (MEDIA_URL,) # TODO … -
How to use JavaScript to validate form before submit in Django?
I have an HTML page, there are a form and 5 checkboxes in the form. All the checkboxes should be clicked, then the form can be submitted out. I want to check if all the checkboxes clicked, this sounds needs JavaScript. Thus I wrote a JavaScript function in the , but it didn't work. The pages go to the views.py. How should I do to check the checkboxes? <form method="POST" action="{% url 'main' %}" onsubmit="return check_fields()" > -
When Trying to Run Pipenv Shell: 'powershell.exe' is not recognized as an internal or external command, operable program or batch file
I have Pipenv installed and everytime I try Pipenv shell I get this message Launching subshell in virtual environment… 'powershell.exe' is not recognized as an internal or external command, operable program or batch file. I tried run and run works, but for some reason shell doesn't. I think it may be a path error but I am not sure. Any and all help is appreciated, thanks. -
Is there a way to use pdf data from scraping without saving the file?
I am trying to use a pdf after scraping it from a website. I would like to use the content directly without actually saving the file on my computer. Here's what I have till now, import libgen_scraper if __name__ =='__main__': context = {} query = 'life of pi' qlist = libgen_scraper.scraper(query) context['Content'] = libgen_scraper.get_content(qlist) print(context['Content']) libgen_scraper.py from bs4 import BeautifulSoup as bs import requests # if __name__ == '__main__': def scraper(search_entry): books_list = [] # search_entry = 'life of pi' search_name=search_entry.replace(' ', '+') url = 'http://libgen.is/search.php?req='+search_name+'&lg_topic=libgen&open=0&view=simple&res=25&phrase=1&column=def' # print("Searching:", url) response = requests.get(url, timeout=10) content = bs(response.content, "html.parser") tables = content.findAll('table') #findinf tables tr_tag = tables[2].findAll('tr') #in the thrid table is all the useful info for tr_tag_iterator in tr_tag: if tr_tag_iterator is not tr_tag[0]: #except the first tr tag, all others contain info of book td_tag=tr_tag_iterator.findAll('td') a_tag=td_tag[2].findAll('a') #in the third td tag, book name is present a_tag=str(a_tag) a_tag=a_tag.lower() #converting all to lower case to compare with search entry if(a_tag.find(search_entry)) is not -1: # a_tag=a_tag[a_tag.find(search_entry):-(len(a_tag)-len(search_entry)-a_tag.find(search_entry))] #shortening the result a_tag=a_tag[a_tag.find(search_entry):] a_tag=a_tag[:-(len(a_tag)-(a_tag.find('<')))] #removing everything after '<' # print("Book:", a_tag) #corresponding author td tag author=str(td_tag[1])#author td tag author=author[author.find('author')+8:-9] #removing all junk till author name, and end tags #8 was added above to compensate for the …