Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django render django-tag from html
Does anyone know if you can have a django tag, like {{ val }} render another tag within it? Something like: {{ val }} where val="{% static 'path/to/file' %}" and have that render the static file? The reason why i am asking is because i am trying to write easy pages with markdown and have a django app template render them for me with {{ val | markdown | safe }} now everything was fine locally because i was using relative paths for image links, however in production these all broke because they were not using {% static %}. So my goal is to try to swap the markdown links with the proper django static tags but i realize that django does not render a nested tag (or at least i was not able to find a way for it to do it). I am open to suggestions if there is an alternative better way as well since i've been at this for a few days! Thanks for the help in advance. -
Docker Postgresql Django Error - django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution
I have been trying to deploy a docker django postgresql application. docker-compose.prod.yml ... services: web: build: context: . dockerfile: Dockerfile.prod restart: always container_name: web command: gunicorn django_app.wsgi:application --bind 0.0.0.0:80 volumes: - static_volume:/static - media_volume:/media expose: - 80 env_file: - ./.env.prod depends_on: - db db: image: postgres:13.4-alpine container_name: db volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.db ... .env.db POSTGRES_USER=user1 POSTGRES_PASSWORD=password1 POSTGRES_DB=prod_db .env.prod ... SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=prod_db SQL_USER=user1 SQL_PASSWORD=password1 SQL_HOST=db SQL_PORT=5432 DATABASE=postgres ... settings.py ... DATABASES = { 'default': { "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"), "NAME": os.environ.get("SQL_DATABASE", os.path.join(BASE_DIR, "db.sqlite3")), "USER": os.environ.get("SQL_USER", "user"), "PASSWORD": os.environ.get("SQL_PASSWORD", "password"), "HOST": os.environ.get("SQL_HOST", "localhost"), "PORT": os.environ.get("SQL_PORT", "5432") } } ... Full error message web | File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect web | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web | django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution Resolution attempts: testing with different postgresql image versions. setting POSTGRES_HOST_AUTH_METHOD to password and trust without success. changing password and username many times changing db name adding 'restart: always' to 'web' in docker-compose Do you have any idea whats required to resolve this error? If you require further details on my docker codebase to resolve this please let me know. Thanks -
What are the best plugins for django-cms in 2020?
After following the tutorial and building some pages I noticed that it doesn't compare for example to Elementor in Wordpress. I don't want to use Wordpress or PHP and I want to stick to learning python. What good plugins do you guys recommend? These is what my settings installed apps looks like at the moment: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'cms', 'menus', 'treebeard', 'djangocms_admin_style', 'sekizai', 'filer', 'easy_thumbnails', 'mptt', 'djangocms_text_ckeditor', 'djangocms_link', 'djangocms_file', 'djangocms_picture', 'djangocms_video', 'djangocms_googlemap', 'djangocms_snippet', 'djangocms_style', ] -
Check if a field is left empty - Django
Is there a way in Django to detect if a field is empty, and by this I mean detect if a field is left empty for every entry of a model submitted? -
Automatic ID Field Returning 'None' in Django
Hi I'm a beginner in Django trying to create a program that will save a model with some input. (Eventually I'll be using a form for that input but the request.POST would contains things I want to send to multiple different places so I can't just use a ModelForm) This is the code for the model: class Bid(models.Model): bid_owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner") bid_value = models.DecimalField(max_digits=6, decimal_places=2) bid_no = models.IntegerField(default=0, null = True, blank=True) bid_open = models.BooleanField(default=True, null = True, blank=True) bid_winner = models.ForeignKey(User, blank=True, default="None", null=True, on_delete=models.CASCADE, related_name="winner") def __str__(self): return f"My ID is {self.id} and this is {self.bid_owner}'s listing" and this is the code I'm calling in views.py: def bar(request): foo = Bid(bid_owner = request.user, bid_value = 25) foo.save() But it keeps bringing up the error " Field 'id' expected a number but got None". From the documentation I've seen the contents of the id field should automatically generate during saving so I'm at a loss on how to solve this. In rendering an HttpResponse showing the contents of 'foo' everything seems to be working except for the id. -
Right way to create nested objects and custom create method
If I use create method redefinition, which type of create objects should I use? Model.objects.create(...) or super.create(...). Both works as expected. What is best practice? Sry for stupid wording of the question. def create(self, validated_data): nested_data = validated_data.pop('nesteds', None) # THIS ONE instance = MODEL.objects.create(**validated_data) # OR THIS instance = super().create(validated_data) -
Error Submitting a form in Django - django.db.utils.IntegrityError: NOT NULL constraint failed: account_deal.company_id
I'm working on a form that takes value from another model, and everything is loaded correctly, but when I submit the data the form is showing the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: account_deal.company_id The consensus is that you have to add blank=True,null=True but that only prevents the error if the user doesn't type any data, in this case, I'm using an auto-generated date, so not sure why am I getting this error. views.py def close_lead(request): if request.method == 'POST': deal_form = DealForm(request.POST) if deal_form.is_valid(): deal_form.save() messages.success(request, 'You have successfully updated the status from open to Close') id = request.GET.get('project_id', '') obj = Leads.objects.get(project_id=id) obj.status = "Closed" obj.save(update_fields=['status']) return HttpResponseRedirect(reverse('dashboard')) else: messages.error(request, 'Error updating your Form') else: id = request.GET.get('project_id', '') obj = get_object_or_404(Leads, project_id=id) m = obj.__dict__ keys = Leads.objects.get(project_id=m['project_id']) form_dict = {'project_id':keys.project_id, 'agent':keys.agent, 'client':keys.point_of_contact, 'company':keys.company, 'service':keys.services } form = NewDealForm(request.POST or None,initial = form_dict) return render(request, "account/close_lead.html", {'form':form}) models.py from django.db import models from django.conf import settings from django_countries.fields import CountryField from phone_field import PhoneField from djmoney.models.fields import MoneyField from ckeditor.fields import RichTextField from django.utils import timezone class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) email = models.EmailField(blank=True,null=True, unique=True) role = models.TextField(blank=True) location = models.TextField(blank=True) photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) … -
How to handle three functions with celery in django?
I'm having a three function in my django site views but I can only run one. I have never used celery, can you help me to transform this into the celery tasks? As you can see, I want to save document which is uploaded by user, and then I want to do some pandas stuff with that file, and after that I want to show pandas stuff in html page. This is forms.py class DocumentForm(forms.Form): docfile = forms.FileField(label='Select a file') This is views.py def save_exls(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() return redirect('html_exls') else: form = DocumentForm() documents = Document.objects.all() context = {'documents': documents, 'form': form,} return render(request, 'list.html', context) def pandas_exls(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) writer = pd.ExcelWriter(output) for name, df in dfs.items(): #pandas stuff done.to_excel(writer, sheet_name=name) output.seek(0) response = HttpResponse( output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response else: form = DocumentForm() return render(request, 'list.html', {'form': form}) def html_exls(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) writer … -
I need it a proxy webserver
Good night, i'm sorry for my bad english, i'm from colombia, this happening is in my job i give a web server in python style PHProxy, i wait me understand, help me, please, is my code, for example, show the page google, how the page (https://www.proxysite.com/) and return a views in Django 3.2, i want a proxysite, Someone know i how to build?: from http.server import BaseHTTPRequestHandler, HTTPServer import time hostName = "localhost" serverPort = 8080 class MyServer(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(bytes("<html><head><title>https://myorg.org</title></head>", "utf-8")) self.wfile.write(bytes("<p>Request: %s</p>" % self.path, "utf-8")) self.wfile.write(bytes("<body>", "utf-8")) self.wfile.write(bytes("<p>I need it return another pages.</p>", "utf-8")) self.wfile.write(bytes("</body></html>", "utf-8")) if __name__ == "__main__": webServer = HTTPServer((hostName, serverPort), MyServer) print("Server started http://%s:%s" % (hostName, serverPort)) try: webServer.serve_forever() except KeyboardInterrupt: pass webServer.server_close() print("Server stopped.") -
How Session App Public-Key-Based Auth Works? And How to Apply It on Django App?
I am looking to implement this method of authentication on Django application. How it's works? And how to implement it ? The commonly expected user experience of being able to recover an account using a username and password is not possible. Instead, users are prompted to write down their long-term private key (represented as a mnemonic seed, referred to within Session as a recovery phrase) upon account generation. A user can use this backup key to recover their account if their device is lost or destroyed, and the user’s contacts will be able to continue contacting that same user account, rather than having to re-initiate contact with a new key. https://getsession.org/faq -
How to set a proxy model for foreign key query set in Django?
I have two models Parent and Child: class Parent(models.Model): some_field = models.IntegerField() class Child(models.Model): objects = models.Manager() custom_objects = managers.CustomManager() parent = models.ForeignKey(Parent) And one proxy model for Child: class ProxyChild(Child): class Meta: proxy = True If i want to get children of parent using custom manager i can do this: children = parent.child_set(manager='custom_objects').all() How can i get children of parent using ProxyChild, i think about this but it's not working: children = parent.child_set(model=ProxyChild).all() I need to get the set exactly through parent.child_set because I need access to the parent fields through child without additional queries to the database. Using ProxyChild.objects.filter(parent=parent).select_related('parent') has two cons: It is heavier. If i want to use a proxy model for parent and then filter the children then Django set the original class of parent(not proxy), for example: class ProxyParent(Parent): class Meta: proxy = True parent = ProxyParent.objects.all().first() child = ProxyChild.objects.filter(parent=parent).select_related('parent').first() print(child.parent) child.parent will be instance of Parent class not ProxyParent -
Are there advantages to using IntegerChoices field in a Django model if it's not shown to users?
I'm using IntegerChoices in my Django (3.2) model. class AType(db.IntegerChoices): UNKNOWN = 0, 'Unknown' SOMETHING = 1, 'Something' ANOTHER_THING = 2, 'Another thing' A_THIRD_THING = 3, 'A third thing' class MyObject(models.Model): a_type = db.IntegerField(choices=AType.choices) (I've changed the choices to be more generic.) Every time I add a value to AType, it produces a DB migration, which I faithfully apply. a_type is strictly behind the scenes. Users never see it, so it's only in the admin UI, but I don't need it to be editable. So forms aren't really used. Is there any impact on the DB (e.g., constraints) of these migrations? Is there any other utility to having an IntegerChoices field, given that it's not displayed to a (non-staff) user, and not in a form? If there's no utility, I'm thinking of just changing MyObject.a_type to an IntegerField, and continuing to use AType everywhere, but not having all the migrations. -
How to upload multiple files in Django using Dropzone js?
Info: I want to upload multiple files using Dropzone js in Django project. I have two models. One for the Post and the other would be for the File. My files model would have a foreignkey to the Post model. About my Views.py when the user is filling out the form post he has to complete the Files form too for the post. Fine: When i submit the Ajax_file_uploads form instead of using Dropzone.js multiple selected files are attached with single Post instance. Problem: If i try to upload multiple files using Dropzone.js Multiple articles are created along with multiple files when I submit the form. Any help would be much appreciated! models.py class Post(models.Model): title = models.CharField(max_length=100, blank=True) content = models.TextField(blank=True) class FileAttach(models.Model): file = models.FileField(upload_to='uploads/') post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='file_attach', null=True) views.py def Ajax_file_uploads(request): if request.method == "POST": p_form = PostForm(request.POST or None) form = AttachForm(request.POST or None, request.FILES) if p_form.is_valid(): art = p_form.save(commit=False) art.user = request.user art.save() files = request.FILES.getlist('file') if form.is_valid(): for f in files: file_instance = FileAttach(file=f, post=art) file_instance.save() return JsonResponse({"error": False, "message": "Uploaded Successfully"}) else: return JsonResponse({"error": True, "errors": p_form.errors}) else: p_form = PostForm() form = AttachForm() return render(request, "upload/api.html", {"p_form": p_form, "form": form}) … -
How To Fix "127.0.0.1 redirected you too many times. ERR_TOO_MANY_REDIRECTS" Django Permission Issue
How To Fix Django 127.0.0.1 redirected you too many times. ERR_TOO_MANY_REDIRECTS in python Whenever I Login With Agent User. Where Agent Only Have Permissions to Access Leads Page and Agent Can't See Any other pages. But When I open /lead It Raise An Error 127.0.0.1 redirected you too many times. ERR_TOO_MANY_REDIRECTS. If I Login With An Organizer User. I Can Visit Leads Page. But If I Login With an Agent. There i can see on navbar leads page but if I click on It's Raise Error 127.0.0.1 redirected you too many times. ERR_TOO_MANY_REDIRECTS App Views.py Code: https://paste.pythondiscord.com/kifimifida.rb App Url.py Code: https://paste.pythondiscord.com/emewavafay.lua app models.py Code: https://paste.pythondiscord.com/upaloqaduh.py -
HTMX/Django: Why does hx-post="." post to the wrong endpoint?
I am trying to get a very basic CRUD example working via htmx and django by adding a simple note/comment to a bookmark. I do not know why my submit button is going to the wrong endpoint, and I am hoping you might share some light into this matter. I have attached some questions to the bottom of this question. Wrong: HTTP POST /notebook/ 405 [0.12, 127.0.0.1:50193] Wanted: HTTP POST /b/<int:pk>/add-note/ Urls: path('b/<int:pk>/add-note/', add_bookmark_note, name="add-bookmark-note") View: @login_required def add_bookmark_note(request, pk): if request.method == "POST": bookmark = get_object_or_404(Bookmark, pk) note = request.POST.get('bookmark_note') if note: old_note = Comment.objects.filter(user=request.user, bookmark=bookmark).first() if old_note: old_note.comment = note old_note.save() print("updated") else: Comment.objects.create(comment=note, user=request.user, bookmark_id=pk) print("created") return render(request, "bookmark/htmx/bookmark_form.html", context={ "form": CommentForm }) Form <div hx-target="this" hx-swap="outerHTML" class=""> <form method="POST"> {% csrf_token %} <textarea name="bookmark_note" class="form-control" id="floatingTextarea2" style="height: 100px">{% if bookmark.comment_set.all.0.comment %}{{ bookmark.comment_set.all.0.comment }}{% endif %}</textarea> <label class="form-text" for="floatingTextarea2">{% trans "Write some notes" %}</label> <button type="submit" hx-post=".">Submit</button> </form> </div> Template <div class="card"> <div class="card-body"> <div hx-target="this"> <p>{{ bookmark.comments|linebreaks }}</p> <button hx-get="{% url 'add-bookmark-note' bookmark.id %}" hx-swap="outerHTML">Add note</button> </div> </div> </div> Questions: Why is hx-post pointing to the wrong endpoint? Why am I getting a NoReverseMatch if I use the url name: <button type="submit" hx-post="{% url 'add-bookmark-note' bookmark.id … -
Is it possible to pass a celery task as parameter in a dango view?
I would like to know if it is possible to pass a celery task as a function in a django (function based) view? -
how to capture image from webcam - django
i'm trying to access webcam and take picture and redirect the picture to my image field (to save into database - postgresql) this is my views.py @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.method == 'POST': images = UploadDocumentFormSet(request.POST,request.FILES) if images.is_valid(): for img in images: if img.is_valid() and img.cleaned_data !={}: img_post = img.save(commit=False) img_post.booking = obj img_post.save() return redirect(reverse_lazy("booking:add_booking",kwargs={"room_no":obj.room_no.room_no})) else: messages.error(request,_('take a picture or choose an image')) images = UploadDocumentFormSet(queryset=Document.objects.none()) return render(request,'booking/add_img.html',{'obj':obj,'images':images}) my models.py class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) def __str__(self): return str(self.booking.id) my forms.py class UploadDocumentsForm(forms.ModelForm): class Meta: model = Document fields = ['docs'] and this is my html + js const player = document.getElementById('player'); const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); const captureButton = document.getElementById('capture'); const constraints = { video: true, }; captureButton.addEventListener('click', () => { // Draw the video frame to the canvas. context.drawImage(player, 0, 0, canvas.width, canvas.height); }); // Attach the video stream to the video element and autoplay. navigator.mediaDevices.getUserMedia(constraints) .then((stream) => { player.srcObject = stream; }); <form action="" method="POST" enctype="multipart/form-data" dir="ltr">{% csrf_token %} {% for form in images.forms %} {{form.id}} {{form.errors}} <div id="main_form" class="text-lg"> </div> <hr> {{images.management_form}} <div class="form-group mt-3" id="images"> {{ form.docs | add_class:'form-control-file' }} </div> <video id="player" controls autoplay></video> <button … -
"Invalid parameter: redirect_uri" Keycloak Setup
I am setting up Keycloak with Django and this is the error I am getting. I have not found any helpful answers on stackoverflow yet. I have tried setting the LOGIN_REDIRECT_URL and LOGIN_REDIRECT_URL_FAILURE variables in settings.py but that had no effect. -
Django HTML page not displaying the content of model, displays object(1) instead
I have this line of html code Calculate distance {{distance}} but instead of grabbing the information from the object, it instead displays Calculate distance Measurements object (1) This is my model class Measurements(models.Model): location = models.CharField(max_length=200) destination = models.CharField(max_length=200) distance = models.DecimalField(max_digits=10, decimal_places=2) created = models.DateTimeField(auto_now_add=True) forms.py from django import forms from .models import Measurements class MeasuremeantModelForm(forms.ModelForm): class Meta: model = Measurements fields = ('distance'), views.py from django.shortcuts import render, get_object_or_404 from .models import Measurements # Create your views here. def calculate_distance_view(request): obj = get_object_or_404(Measurements) context = { 'distance' : obj, } return render(request, 'measurements/main.html', context) I can't figure out why it wouldn't be displaying the contents of the object the object's distance has a value of 2000 -
How to do override the default django email form?
I want to override the email form and add my app name before the URL 'password_reset_confirm' How can I? -
SMTPAuthenticationError when sending email in my Django Project Deployed on Google Cloud
I have deployed my Django Project on Google Cloud. I want emails to be sent on different conditions in my project. The emails are successfully sent when the project is hosted on the development server on the internal IP. However I am facing an SMTP Authentication error when trying to send email on Google Cloud where my project is deployed. Following are my email settings and the error encountered: Email Settings SMTP Authentication Error -
Updates to admin.py not reflected in the django admin page
I'm building a django app and the django admin page doesn't seem to be reflecting the changes I make to admin.py. For example if I want to exclude some fields, or customizing the admin change list, nothing changes in the actual page. The only thing that seems to be reflected properly is the fact that I can register the models, and they will show up. Here's my admin.py from django.contrib import admin from .models import Form, Biuletyn, Ogloszenie, Album class FormAdmin(admin.ModelAdmin): exclude = ('img',) class BiuletynAdmin(admin.ModelAdmin): list_display = ('name', 'date') class OgloszenieAdmin(admin.ModelAdmin): fields = ('name', 'date', 'upload') admin.site.register(Form) admin.site.register(Biuletyn) admin.site.register(Ogloszenie) admin.site.register(Album) P.S. Please ignore the weird model names. The site is actually in a different language :D -
passing data from django view context dictionary to react components
I am trying to create a Django and React full stack web app and using django rest framework to create apis and it is really easy to work with these two when it comes to send data but for login and logout system it is becoming really messy to work with as we cannot get the request.user from a normal fetch request from react. and also passing data from a view context dictionary to react also getting too much difficult for me. I have a view to render index.html whose control is taken over by react and I want to send that if user is authenticated or not to my react component how can I do that? Here is how my view is looking. ```def index(request): authenticated = False if request.user.is_authenticated: authenticated = True context = { 'authenticated':authenticated } return render(request,'index.html',context)``` I want to pass authenticated to react component how can I do it? I have passed it to normal js on index.html but don't know how to pass it to react component. Here is how my index.html looks like. ```<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" … -
Uncaught TypeError: Cannot read properties of null
I wrote this code and now i'm stuck with this error TypeError: Cannot read properties of null (reading 'innerHTML') displayCart(cart); function displayCart(cart) { //cart is perameter actually var cartString = ""; cartString += "<h5>This is your cart</h5>"; var cartIndex = 1; for (var x in cart){ cartString += cartIndex; console.log(document.getElementById("nam" + x).innerHTML +" | " + "Qty:" + cart[x] ); cartString += document.getElementById("nam" + x).innerHTML +" | " + "Qty:" + cart[x] + "</br>" ; cartIndex +=1; } } thank you -
Django - How can add multiple forms according to input enter number
I have an input field where the will customer add a number for buy membership then will get forms according to numbers 1,2, or 5 then will show 1,2, or 5 forms with input fields in which will add data. For example: customer will come to the site and click on buy membership the first page will How many Memberships do you want to buy? ==> input Field in which will add 1,2, or 5 based on how many members enter a show a page to collect information of members I have reached the multiple forms adding by the user with the button. But my desire is that on the first-page user will enter the number of forms which he wants then according to his number I will create the number of forms for him. On that which I have worked with Django formsets you can see my code models.py from django.db import models class MemberShip(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) EXPERIENCE = ( ('First Time', 'First Time'), ('Have skier and snowboard before', 'Have skier and snowboard before'), ) first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) experience = models.CharField(max_length=100, null=True, choices=EXPERIENCE) date_birth = models.CharField(max_length=20, null=True) gender …