Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error message:===Invalid block tag on line 31: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
PLease do let me know where i went wrong>>> -
Django html form: how to only populate field value if it exists?
My Django app has a Person model with some optional text fields, such as: nickname = models.CharField(max_length=20, null=True, blank=True, default='') When a record doesn't have one of these fields populated, it just appears empty in the Django Admin (as expected). I have a little form where a person can update some select fields on the record, and the field appears on the form like so (prefilling the field with the current value): <label class="col-form-label mt-4" for="nickname">Nick name:</label> <input type="text" class="form-control" value="{{ person.nickname }}" id="nickname" name="nickname"> The Problem: For a record where the field is empty, 'None' is shown as the value on the form field, and if you submit the form without removing it, the record is updated with the string 'None' saved for that field. How can I update my code so the form only pre-fills that 'value' if there's actually an existing value to use? -
Method Not Allowed (POST) in Django 3.1
I am new to Django. Practicing in a small project in Dango 3.1 I get the error "Method Not Allowed (POST)". The error appears when a user presses the Guarder (Save) button. Method Not Allowed: /pizarra/comunicado/ [30/Jul/2021 09:10:03] "POST /pizarra/comunicado/ HTTP/1.1" 405 0 Everything was working before and I can't understand what I'm doing wrong. Please if someone can help me. Thanks in advance. comunicado_form.html {% extends 'gestion/base_gestion.html' %} {% block page_content %} <form method="POST" class="form-group"> {% csrf_token %} <div class="col-xl-12 col-md-12 mb-12"> {% if obj %} <div class="card border-left-warning shadow h-100 py-2"> {% else %} <div class="card border-left-success shadow h-100 py-2"> {% endif %} <div class="card-body"> <div class="row no-gutters align-items-center"> <div class="col mr-2"> <div class="text-xs font-weight-bold text-success text-uppercase mb-1"> {% if obj %}Editar{% else %}Nuevo{% endif %} Comunicado </div> <div class="dropdown-divider"></div> <div class="col-sm-8"> <div class="col-8"> <div class="form-group"> <label for="id_contenido">Contenido del mensaje:</label> {{ form.contenido }} </div> </div> <div class="col-3"> <div class="form-group"> <label for="id_fecha_vto">Fecha Vto:</label> {{ form.fecha_vto }} </div> </div> <div class="col-2"> <div class="form-group"> <label for="id_hora_vto">Hora Vto:</label> {{ form.hora_vto }} </div> </div> <div class="col-3"> <div class="form-group"> <label for="id_es_borrador">¿Es Borrador?:</label> {{ form.es_borrador }} </div> </div> <div class="col-2"> <div class="form-group"> <label for="id_es_borrador">Estado:</label> {{ form.estado }} </div> </div> <!-- {{ form.as_p }} --> </div> … -
models.ForeignKey() in django
Here is my code from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) So I'm kinda confused with what models.DateTimeField(default=timezone.now) do, what does "default" mean here? And I'm also confused what models.ForeignKey(User, on_delete=models.CASCADE) do, what is "on_delete=models.CASCADE" do and mean? And is this code ( from django.contrib.auth.models ) a database for users? -
How to change the name of a third party app on Django?
I am using django-allauth and its account app conflicts with my account app. I managed to fix this conflict by creating an app label for allauth.account based on this solution from django.apps import AppConfig class AllAuthAccountConfig(AppConfig): name = 'allauth.account' label = 'allauth_account' verbose_name = 'aullauth_account' and then adding it to installed apps INSTALLED_APPS = ( ..., 'apps.allauth.apps.AllAuthAccountConfig', ..., ) Now, when I try to migrate it gives an error CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0001_initial, 0002_email_max_length in allauth_account). To fix them run 'python manage.py makemigrations --merge' but python manage.py makemigrations --merge also fails with the following error: ValueError: Could not find common ancestor of ['0001_initial', '0002_email_max_length'] How can I change the allauth.account app name so it doesn't conflict with my app or my migations? -
Using Adobe pdf extract API in Django
I am trying to get the InMemoryUploadedFile from django rest api and pass it on to the adobe extract API function. The error says like its not a pdf or something. But i just uploaded the sample pdf that the adobe gave. I am guessing I am wrong somewhere in the source file part, but not sure. Could somebody help? Here is the code for adobe api thingy ''' import logging import os.path from adobe.pdfservices.operation.auth.credentials import Credentials from adobe.pdfservices.operation.exception.exceptions import ServiceApiException, ServiceUsageException, SdkException from adobe.pdfservices.operation.pdfops.options.extractpdf.extract_pdf_options import ExtractPDFOptions from adobe.pdfservices.operation.pdfops.options.extractpdf.extract_element_type import ExtractElementType from adobe.pdfservices.operation.pdfops.options.extractpdf.extract_renditions_element_type import \ ExtractRenditionsElementType from adobe.pdfservices.operation.pdfops.options.extractpdf.table_structure_type import TableStructureType from adobe.pdfservices.operation.execution_context import ExecutionContext from adobe.pdfservices.operation.io.file_ref import FileRef from adobe.pdfservices.operation.pdfops.extract_pdf_operation import ExtractPDFOperation def extract(file_object): logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO")) try: # get base path. # base_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) base_path = os.path.dirname(__file__) # print(base_path, os.path.dirname(__file__), os.path.abspath(__file__)) # print(base_path) # Initial setup, create credentials instance. credentials = Credentials.service_account_credentials_builder() \ .from_file(base_path + "/adobe_credentials/pdfservices-api-credentials.json") \ .build() # Create an ExecutionContext using credentials and create a new operation instance. execution_context = ExecutionContext.create(credentials) extract_pdf_operation = ExtractPDFOperation.create_new() # Set operation input from a source file. # source = FileRef.create_from_local_file( # base_path + "/resources/sample_statement_thiyagaraja.pdf") source = FileRef.create_from_stream( file_object, media_type="application/pdf") extract_pdf_operation.set_input(source) # Build ExtractPDF options and set them into the operation extract_pdf_options: … -
Update status in django field - status CHOICES
I have a model django and I want to update my fields Status Choices: my models.py class Top(core.BaseModel): class Status(models.IntegerChoices): EMPTY = 0,'-----' SEND_CANCEL = 1, 'Send' CANCELLED = 2, 'Cancel' my views.py class TopUpdateView(core.UpdateView): template_name = 'top/update_top.html' form_class = UpdateTopForm @require_POST def cancel_status(request, pk, status): top = get_object_or_404(Top, pk=pk, status=None, user=request.user) top.status= status.CANCELLED top.save(update_fields=['status']) return redirect('top:item-detail') urls.py path('top/<pk>/cancel/', views.cancel_status, name='cancel-status'), template: <button class="btn"> <a href="{% url 'top:cancel-status' object.id %}"> Cancel </button> All what I want here it is update CHOICE field status from EMPTY on CANCELLED when I click on button. But it is does not work (((( I know how to update and save simple field but do not unserstand the best way update Choices Field in view.Anybode please help me! -
authtoken/access token validation in django
So I know there are a lot of DRF packages for auth token authentication but my project uses simple functions as API and I need some auth token type features. It should be able to validate the access token and only then it should give a response. Is there any 3rd party package I can use for the same? -
Django Media File is not found on production (404)
I have wondered around lot of other stackoverflow issues to see if there is a solution but i couldn't work around it. So here is the issue: Nginx.conf location /media/ { alias /root/server/media/; } location /static/ { alias /root/server/static/; } urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static/'),) STATIC_ROOT = os.path.join(BASE_DIR, '/static/') MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' wsgi.py application = WhiteNoise(application, root=os.path.join(BASE_DIR, 'static')) application = WhiteNoise(application, root=os.path.join(BASE_DIR, 'media')) I have set everything as necessary, i check the directory (root/server/media) and images are there. But when i enter the link : media/images/1.png , it gives me 404 (Not found) error. Does anybody know why? -
How to make nginx check authentication status from the old backend in the new backend?
I have two Django backends (old and new): Old backend (old endpoints worked with authentication system based on jwt tokens) New backend (new endpoints without any authentication system) I can't add authentication system for the new backend for some reasons, so I want to check user authentication status from the old backend and give access for the new backend new endpoints if this user logged. So, I tried to use ngx_http_auth_request_module, but I get 404 error instead of json response after succeded case: [error] 32#32: *6 "/etc/nginx/html/v2.0/private/index.html" is not found (2: No such file or directory) while sending to client, client: 172.18.0.1, server: , request: "POST /v2.0/private/ HTTP/1.1", host: "localhost" nginx.conf: server { listen 80 default_server; location /v1.0/ { proxy_pass http://old_backend:8000; } location /v2.0/ { proxy_pass http://new_backend:8002; } location /v2.0/private/ { auth_request /v1.0/profile/; } location = /v1.0/profile/ { proxy_pass_request_body off; proxy_set_header Content-Length ""; proxy_pass http://old_backend:8000/v1.0/profile/; } Can I solve my problem with ngx_http_auth_request_module or do I need to find anouther solution? -
Django - Displaying alert messages in base template
I am displaying alert messages in my base template with a simple for loop. My issue is that when the message gets displayed it pushes down the div for whatever page is getting the alert. Obviously this is because for the alert I am creating a new div and inserting it at the top of the page but I was wondering if there was a better way to do this? I could solve this issue but just hard coding the message inside of the div into the specific pages where I want the message to be displayed but I would prefer leaving it in the base template if possible. Is there some way with css that I could possibly make the div display on top of another div maybe? Or maybe simply just changing how my messages displayed will fix it? I have tried a few different solutions and fit for what I need. Any help is greatly appreciated! base template: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %} {% endblock %}</title> {% block extra_head %} {% endblock %} <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> {% block css_files %} … -
How to increment slot field when booking an appointment
Doctor model class Doctor(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) qualifications = models.CharField(max_length=100) expertise = models.CharField(max_length=100, default='Cardiac') fee = models.IntegerField(default=500) slots = models.IntegerField(default=0) def incSlots(self): self.slots = self.slots + 1 Appointment model class Appointment(models.Model): appointment_id = models.AutoField(primary_key=True) patient = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) blood_pressure = models.CharField(max_length=10) BMI = models.CharField(max_length=10) blood_sugar = models.CharField(max_length=10) HB = models.CharField(max_length=10) platelets = models.CharField(max_length=10) date = models.CharField(max_length=30) time = models.CharField(max_length=30) detail = models.TextField() doc = models.OneToOneField(Doctor, on_delete=models.CASCADE) Appointment view def appointment(request): docname = request.POST.get('doc_name') if request.method == 'POST': form = AppointmentForm(request.POST) if form.is_valid(): form.doc.incSlots() form.save() return redirect('success') else: print(form.errors) form = AppointmentForm(initial={"patient":request.user, "doc_name": docname}) return render(request, 'appointment.html', {'form': form}) I want to increment "slot" field when booking an appointment, I have no idea how to do it, i am new to django, i'll appreciate any help Thank you. -
How to get the limit value from the django API URL
from the below Url, I need the limit, to do some operations in my view http://127.0.0.1:8000/emp/?limit=10&offset=5 I tried using the below things but no luck if request.limit>5: do something... if kwargs['limit'] >5: do something.... -
Relation does not exist error in Django after postgresql integration
I used sqlite3 during development, then changed my database settings to postgresql: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test2', 'USER': 'postgres', 'PASSWORD': 'aman', 'HOST': 'localhost', 'PORT': '5432', } } Regardless of any command I write, it gives me the error: django.db.utils.ProgrammingError: relation "taksist_category" does not exist LINE 1: ...st_category"."id", "taksist_category"."name" FROM "taksist_c... Category model exists inside taksist application. If I take back my database settings to sqlite3, then application runs successfully. I cannot even run my server. Even if there is a problem with my model taksist/Category, my application should run. Here strange thing is whatever command is written, I got this error. I cannot do makemigrations, migrate, runserver. What did I do to solve the issue: deleted migrations folder, and tried makemigrations I created empty migrations folder with init.py inside, and tried makemigrations python manage.py migrate --fake none of above worked. Any help of yours is appreciated. thank you in advance. -
Download a zip file with Django, no errors showing but nothing happens
I'm currently developping a django web application and I'm struggling for downloading a zip file I'm trying to create a zip with nifti binary files. I get the path of my data with this form : <form action="" method="POST" id="form-sequence"> {% csrf_token %} <input type="hidden" name="data-path" id="data-path" value=""> </form> And I use jquery for posting the form like that (the variable data-path is an array of path) : document.getElementById("data-path").value = data_path; var form = $("#form-sequence"); var posting = $.post(form.attr('action'), form.serialize()); posting.done(function(data) { console.log("Exported !") }); As a result I got a 200 response from this request (I linked a screenshot of the response) With Django, in my view, I get the form data like this : if (request.POST.get('data-path')): data_path = request.POST.get('data-path').split(",") print(f"{data_path = }") zip_dir = "C:/dir/to/zip/" zip_path = os.path.normpath(os.path.join(zip_dir, "data.zip")) zip_file = zipfile.ZipFile(zip_path, "w") for file in data_path: filename = os.path.normpath(file) zip_file.write(filename) zip_file.close() # wrapper = FileWrapper(open(zip_path, 'rb')) # response = HttpResponse(wrapper, content_type="application/zip") response = HttpResponse(open(zip_path, 'rb'), content_type="application/zip") response["Content-Disposition"] = "attachment; filename=data.zip" print(response) return response As you can see, I tried to use FileWrapper without success. I also printed the response in the view file and I always got : <HttpResponse status_code=200, "application/zip"> But unfortunately, the Windows popup for … -
Django : How to get month data in week wise format in django( Eg : I need last 50 days of data in 10 , 10 , 10, 10 , 10 format )
Django query : Get last 50 days of data from database in ( 10 days, 10 days etc.. ) format -
Usage django.template.engine.Enginge.get_default
What for Enginge.get_default method? Do i need to call it if i want to render a string? What does i mean: from django.template import Template, Context template_code = "Hello, {{ friend_name }}" context = Context({"friend_name": "Andrew"}) Template(template_code).render(context) Or from django.template.engine import Enginge get_template = Enginge.get_default().from_string template_code = "Hello, {{ friend_name }}" context = Context({"friend_name": "Andrew"}) get_template(template_code).render(context) I am writing a reusable application and want to know if using Enginge.get_default is similar to get_user_model (in case of redefinition). If yes, should get_default be constantly called? Or only need to get the value once by storing the value in a namespace variable. -
Django can't load ckeditor in the admin page
This is my settings.py file INSTALLED_APPS = [ 'search.apps.SearchConfig', 'user.apps.UserConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django_node_assets', 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_BASEPATH = "./search/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = "/media/" This is the models.py file from ckeditor.fields import RichTextField from ckeditor_uploader.fields import RichTextUploadingField class Content(models.Model): heading = models.ForeignKey(SubTopics, on_delete=models.CASCADE) content = RichTextField() def __str__(self): return self.heading.heading This rich text editor is not showing on the admin page. Even no text field is shown on the page, just blank space. -
No User matches a given query Django
While trying to display post-detail template in a blog app, I get an error No User matches a given query. In my models I am inheriting from User model. What seems the problem? # Third party imports. from django.contrib.auth.models import User from django.db import models from django.urls import reverse from django.utils import timezone class Post(models.Model): """ Creates Model for a post in the database. """ title = models.CharField(max_length=100) sub_title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): """ A string representation of the post model. """ return self.title def get_absolute_url(self): """ Creates the absolute url for a particular post. """ return reverse('blog:post-detail', kwargs={'pk': self.pk}) views.py class PostDetailView(DetailView): """ View for a post's details """ model = Post template_name ='blog/post_detail.html' context_object_name = 'posts' paginate_by = 3 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') home.html {% extends 'blog/base.html' %} {% load static %} {% block crumb %} {% for post in posts %} <div class="post-preview"> <a href="{% url 'blog:post-detail' post.id %}"> <h2 class="post-title">{{ post.title }} </h2> <h3 class="post-subtitle">{{ post.sub_title }} </h3> </a> <p class="post-meta" style="font-weight: 300;"> Posted by <a class="text-muted">{{post.author}} on {{ post.date_posted|date:"F d, Y" }}</a> </p> </div> <hr class="my-4" /> {% endfor %} {% … -
How to add status to registered accounts with google account
I want to add status to the accounts registered with the google / facebook account in the postgreSql database, I added the status column in the database. What I do: When I register with my google / facebook account I direct the user to a page where he has a status to choose and depending on the status to be sent to a page, but no status is saved in the database. Any ideas? In the Python language with Django framework. Thanks -
django how to disable & enable email verification in admin panel
I'm working on a Django project and i want to be able to disable or enable email registration verification in admin panel, with a radio button, if it's set to ON, when user registers to site need to verify email, but if it's set to OFF user account activate after registration and don't need to activate account with email verification -
I am having trouble in passing a specific image in my template from Django models
Models.py class BaseLogo(models.Model): logolabel = models.CharField(max_length = 100, null = False, blank = False) logoimage = models.ImageField(null = False, blank = False) def __str__(self): return self.logolabel Views.py def base(request): baselogo = get_object_or_404(BaseLogo, pk=1) context = { 'baselogo': baselogo, } return render(request, 'pages/base.html', context) Template <a class="nav-brand" href="{% url 'main-home' %}"> <img src="{{ baselogo.logoimage.url }}" alt="VCAAT Logo" title="VCAAT Logo" style="width: 60px; height: 60px; float: left; margin-left: 20px; margin-right: 20px;"></a> Notes: It is in NavBar I have a gallery app and I also have profile pictures, so I was able to pass images before. The website is uploaded in pythonanywhere. I have an image uploaded in admin page I don't understand what is wrong why my image (logo) would not appear. -
Append server name in a API response -- Django rest framework
I have been trying to create a API with Django restframework. There is a Image field in the API which is giving a relative path. I would like to have absolute path or name of the server to append before the Image field. But its throwing an error TypeError: string indices must be integers I believe the json that I created from the ordered dict is a string and is not giving expected output. Problem: I need to access the json keys and append server name in it. I tried the following for it. views.py def get_individualmember_details(request): if request.method == 'GET': serializer = MasterIndividualMembersSerializer(MasterIndividualMembers.objects.all(), many=True) result = json.dumps(serializer.data) print(result) for row in result: if row["member_photos"]["image"]: row["member_photos"]["image"] = request.META['HTTP_HOST'] + "/" + row["member_photos"]["image"] result = json.dumps(result) return JsonResponse(json.loads(result), safe=False) expected output: [ { "individualmemberId": "1", "member_photos": [ { "id": 25, "image": "http://127.0.0.1:8000/individualmemberphotos/user.jpeg", // need to append servername here "individualmemberId": "1" } ], ... ... ] current output without the logic above: [ { "individualmemberId": "1", "member_photos": [ { "id": 25, "image": "individualmemberphotos/user.jpeg", "individualmemberId": "1" } ], ... ... ] Please suggest how to append the server name or a string before any json key. Thanks in advance! -
Using distinct() function in list. distinct function is not working in list
I am building a Blog App AND I am filtering many queries in one view. I mean, I am filtering two posts which are posted by request.user and By request.user's friends. AND appending all the filtered results in list. BUT when i append all the results then duplicate posts are showing in browser. Then i used distinct() function in list then the error is showing :- 'list' object has no attribute 'distinct' models.py class BlogPost(models.Model): user = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) title = models.CharField(max_length=500,default='') favourites = models.ManyToManyField(User, related_name='favourites ', blank=True) views.py def all_blogposts(request): ALL_POSTS = [].distinct() #Adding user's post in the list. user_post = BlogPost.objects.filter(favourites =request.user)[:5] for post in user_post: ALL_POSTS.append(post) #Adding friend's post in the list. all_posts = BlogPost.objects.all() requested = request.user.profile.friends.all() for user_p in requested: for sets in user_p.user.blogpost_set.all(): ALL_POSTS.append(sets) context = {'ALL_POSTS':ALL_POSTS} return render(request, 'all_posts.html', context) When i use distinct() and check then the error is keep showing. I also tried to use distinct() after [:5] in user_post but then it shows. Cannot create distinct fields once a slice has been taken. Many Duplicate posts are showing. Any help would be Much Appreciated. Thank You in Advance. -
How can I do a Django query where I can filter on a dict?
I am trying to do a query using Django but I got a problem, here is my query : A = User.objects.filter(country['Europe']['South']='Italy') But it does not work ... Could you help me please ? Thank you very much !