Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Migration does not create column in database
makemigrations and migrate are working fine with no error. but when i check database it does not created heres the model: class Services(models.Model): service_id = models.AutoField(primary_key=True) parent_id = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True,related_name='sub_service') service_name = models.CharField(max_length=100) service_icon = models.CharField(max_length=500, null=True, blank=True) service_image = models.CharField(max_length=500, null=True, blank=True) category_id = models.ForeignKey(Category,on_delete=models.CASCADE) active_status = models.BooleanField(default=True) type = models.SmallIntegerField(blank=True, null=True) service_description = models.TextField( null=True, blank=True) duration = models.CharField(max_length=100,null=True,blank=True) I have added duration field later and its not giving me any error while running api django.db.utils.ProgrammingError: column service_list_services.duration does not exist LINE 1: ...", "service_list_services"."service_description", "service_l... i have tried deleting migration files and then migrating but still.. its not giving error while migrating but doesnot create row. tried this python manage.py migrate --fake still same -
'SettingsReference' object has no attribute '_meta'
Getting this error after changing the custom user table in the mid-project also after changing the name of the custom user class. -
Different URL Based On Condition In Django
I have a url like this: app_name = 'vineyards' urlpatterns = [ path('<str:parent>/<str:region>/<slug:slug>/', vineyard_detail, name="detail"), ] This is the absolute url in model: def get_absolute_url(self): return reverse('vineyards:detail', kwargs={'parent': self.region.region_parent, 'region': self.region.slug, 'slug': self.slug}) The <str:parent>/ is optional, it can be null. I want to ignore the <str:parent>/ if it is None So for example, i want the url is something like this: .../something/ Instead of this : .../None/something/ How can i do that? Is it possible? -
Subscription button with data validation
<form class="row row-cols-lg-auto g-2 align-items-center justify-content-end"> <div class="col-12" id="my_form"> <input id="emailfield" type="email" class="form-control" placeholder="Ingresa tu Email" required="required"> </div> <div class="col-12" id="thank_you" style="display: none;"> Gracias por subscribirse! </div> <div class="col-12"> <button type="submit" class="btn btn-primary-soft m-0" name="subscribirse" id="nextStep">Subscribirse</button> </div> </form> enter image description here what the script does is hidde the input element and show the "thanks message" this is fine, but before do this i need it to validate if input emailfield is validated. and show the "thanks message" only if that happent. Thanks! <script> var nextStep = document.querySelector('#nextStep'); nextStep.addEventListener('click', function (e) { e.preventDefault() // Hide first view document.getElementById('my_form').style.display = 'none'; // Show thank you message element document.getElementById('thank_you').style.display = 'block'; }); </script> -
Django Rest Framwork return serializer create() method response from view?
I want to bulk entry of product order. Here is my two models one is Order and another is OrderMap Order model is summary of order and OrderMap stores all of product order details. I have write a create method in OrderSerializer and everything is working ok but i can not trigger response to the view. How to do it? Please help me. Thanks in advanced. Here is my code: serializers.py class OrderMapSerializer(serializers.ModelSerializer): OrderNo = serializers.ReadOnlyField(source='order.orderno') class Meta: model = OrderMap fields = ('id', 'OrderNo', 'ItemCode', 'OrderQty', 'ReceivedQty') class OrderSerializer(serializers.ModelSerializer): OrderMapData = OrderMapSerializer(many=True, source='ordermaporder') class Meta: model = Order fields = "__all__" def create(self, validated_data): ordermap_set = validated_data.pop('ordermaporder') add_pro = Order.objects.create(**validated_data) for data in ordermap_set: OrderMap.objects.create( OrderNo=add_pro, OrderQty=data.get('OrderQty'), ItemCode=data.get('ItemCode'), ReceivedQty=data.get('ReceivedQty') ) return add_pro I want to return response from my view like this: if(): dict_response = {"error": False, "Title": "Success", "ico": "successIcon", "message": "Wellcome! Product item successfully added."} else: exceptions = [] for key in serializer.errors.keys(): exceptions.append({"field": key, "message": serializer.errors[key][0]}) dict_response = { "error": True, "status": 400, "message": "Your submitted data was not valid - please correct the below errors", "exception": exceptions } return Response(dict_response) -
Django Common Field Methods name and
clean(value, instance)—Validates the given value is appropriate for the model, and the instance it's assigned to. Internally, this defers to both to_python() and validate(), as well as processing a list of validators that were defined when the field was instantiated. It will return a corrected value if everything was valid, and will raise django.core.exceptions. ValidationError otherwise. • contribute_to_class(cls, name)—Configures the field for the class it’s attached to. One of the most important methods on fields, this is called when ModelBase is processing the attributes that were assigned to the model’s class definition. The cls argument is the model class it was assigned to, and name is the name it was given when it was assigned there. This allows fields the opportunity to perform any additional setup or configuration, based on this information. It usually doesn’t need to be called directly, but can be a useful way of applying a field to a previously-processed model. • db_type(connection)—Returns the database-specific column definition necessary for this field to store its data. Typically, this is only used internally, but as with some of the other attributes listed, if an application needs to access the database directly using some other tool, this can be a … -
How to scroll lock a Django HTML Web Page
I am currently using a page that has a list of in-line forms However when the user enters submits each form (line) they are sent back to the top of the page. This becomes really tedious as the users need to enter data quickly and can't when they need to scroll for 2 minutes every time they add an entry. Does anyone know how to implement a scroll lock to stock this from happening -
Why same lines of code taking longer time to execute in Django's project environment than running as python script?
I have executed few line of code inside my Django project environment as well as a simple python script. Their code execution times are as follows Django project's environment (django_env) vak@vishal:/vk$ python3 cev05_script.py speed: 691.2 mm/s Code Execution Time : 43.4 sec Run outside Django's environment as a python script. (py_practice) vak@vishal:/vk$ python3 cev05_script.py speed: 691.2 mm/s Code Execution Time : 0.67 sec I have created environments with 'pipenv' package. Why this is happening? Thanks! -
Django Custom Storage System
I want to build a custom storage system in Django, so that users can upload files to a mounted location. I already saw the official Django guide on this matter (https://docs.djangoproject.com/en/3.2/howto/custom-file-storage/), but I can't wrap my head around it. The idea is to use another location on the server, not the MEDIA_ROOT, and it should also be possible to access the files outside the app. Could someone give me some ideas? -
Filter List in Django JSON Field with string contains
My Django JSON field contains a list of values like ["N05BB01", "R06AX33"]. atc_code = JSONField(default=list()) I would like to filter this field, for 'does any string in list contain "N05"?'. -
postgres wont list my database in heidisql
I seem to have done everything right, but still it wont populate my table in heidisql. I am using docker. My Heidi is like this. I have put my database name in database which is hidden above. Also my docker is up with both django and postgres running. After opening heidisql, it is empty in public, authentication is working but it wont populates the tables. My local.yml is like this: env_file: - ./.envs/.local/.postgres ports: - "5432:5432" my postgres file in local env POSTGRES_HOST=postgres POSTGRES_PORT=5432 POSTGRES_DB=example POSTGRES_USER=aYeyCmaatmik POSTGRES_PASSWORD=oyOucWOu185tUIPavYeyCmXUncS Here in heidi, i have used the superuser postgres which was initally setup during the installation not the above one in postgres file which is the correct way i think. -
Django crispy form model formset - to STOP showing DELETE column
I am using Django 3.2 and crispy-forms 1.11.2 I have a model and form defined like this: /path/to/myapp/models.py class Foo(models.Model): pass class FooChild(models.Model): parent = models.ForeignKey(Foo, on_delete=models.CASCADE) title = models.CharField(max_length=16) /path/to/myapp/forms.py class FooChildForm(ModelForm): class Meta: model = FooChild fields = "__all__" class FooChildFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_method = 'post' self.layout = Layout( 'title', ) self.render_required_fields = True /path/to/myapp/views.py class FooCreateView(CreateView): model = Foo def __init__(self, **kwargs): super().__init__(**kwargs) self.choice_formset = inlineformset_factory(Foo, Child, form=FooChild, extra=9) def get(self, request, *args, **kwargs): form = self.form_class() p = self.model() formset = self.choice_formset(instance=p) helper = ChildFormSetHelper() helper.template = 'bootstrap/table_inline_formset.html' helper.form_tag = False return render(request, 'myapp/create.html', {'form' : form, 'formset': formset, 'helper': helper}) /path/to/myapp/templates/myapp/create.html {% block content %} <div class="container-lg"> <form id="frm-foo-create" method="post"> {% csrf_token %} <div class="row" style="margin: 30px 0px;"> <div class="col-lg-12"> <h2>Create a New Foo</h2> <br /> {% crispy form %} {{ form|as_crispy_errors }} {% crispy formset helper %} {{ formset.management_form }} </div> <!-- col-lg-12--> </div> <!-- row --> <div class="row" style="margin: 30px 0px;"> <div class="col-lg-2"> <input style="width:100%; padding-left: 20px;" type="submit" name="submit" value="Submit" class="btn btn-primary" id="btn-foo-create"> </div> </div> </form> </div> <!-- container --> {% endblock content %} When this page is created, it shows a DELETE column next to the Title column … -
Django serialize returns string instead list [closed]
I Have two models, one of them with a Foreign key, it's the same as you can see in this guide: https://docs.djangoproject.com/en/3.2/topics/serialization/ now I have this code to look for books published in a given year: books = Book.objects.filter(year=year) search_results = serializers.serialize( 'json', books, use_natural_foreign_keys=True, use_natural_primary_key=True, ) I expected to have a list, but I have a string: '[{"name": "test", "author"...' What am I doing wrong? -
unknown django core erorr?
I have created an authentication system using drf and now I want the system to display all the urls when accessing 127.0.0.1:8000/. After rearranging urls, I am getting this error here. [01/Oct/2021 13:02:55] "GET / HTTP/1.1" 500 62761 Internal Server Error: / Traceback (most recent call last): File "C:\Users\******\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: __init__() takes 1 positional argument but 2 were given [01/Oct/2021 13:04:02] "GET / HTTP/1.1" 500 62761 I dont know where is error poining at. core/urls.py from django.urls import include, path from users.views import ApiView urlpatterns = [ path("", ApiView, name="api-view"), path("users/", include("users.urls")), ] users/urls.py from django.urls import path from rest_framework.authtoken.views import obtain_auth_token from . import views urlpatterns = [ path("login/", obtain_auth_token, name="login"), path("logout/", views.Logout.as_view(), name="logout"), path("hello/", views.HelloView.as_view(), name="hello"), path("register/", views.UserCreate.as_view(), name="register"), ] -
how to access to image html tag from django's view?
I've to get access to <img> html tag from django , i'm using webcam to capture multiple images and them into database , but i dont know how use POST.get(img tag) ? here is what im trying .. class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) my views.py @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.method == 'POST': images = request.POST.get('images') print(images) format, imgstr = images.split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) photo = Document.objects.create( booking = obj, docs = data ) photo.save() return redirect(reverse_lazy("booking:add_booking",kwargs={"room_no":obj.room_no.room_no})) else: messages.error(request,_('capture right image ..')) return render(request,'booking/add_img.html',{'obj':obj}) and here is my html and js code const player = document.getElementById('player') const canvas = document.getElementById('canvas') const form = document.getElementById('form') const docs = document.getElementById('document') const captureButton = document.getElementById('capture') const context = canvas.getContext('2d') captureButton.addEventListener('click', (e) => { context.drawImage(player, 0, 0, canvas.width, canvas.height) e.preventDefault(); let new_image = document.createElement('img') new_image.src = canvas.toDataURL() console.log(new_image) new_image.setAttribute("name","images") form.insertAdjacentElement('beforeend',new_image) }); navigator.mediaDevices.getUserMedia({video: true}) .then((stream) => { player.srcObject = stream;}) <style> form *{max-width:20vw;} img{display:inline-block;} canvas{display:none;} </style> <form id="form" action="" method="POST" enctype="multipart/form-data">{% csrf_token %} <video id="player" controls autoplay></video> <button type="button" id="capture">Capture</button> <button>save</button> <canvas id="canvas" width=320 height=240></canvas> </form> is there please a way to achieve it ? i can save one image in this way : const … -
'heroku' is not recognized as an internal or external command
Actually I am trying to host my site live on Heroku and I downloaded Heroku cli also but when i am trying to run any Heroku command it didn't work. I have set environment variable also. help me to find the solution. I used Techstack as: python, Django, sqlite3 and Heroku for hosting. I am following this video and I am sharing link with you: https://www.youtube.com/watch?v=kBwhtEIXGII&list=PL-51WBLyFTg2vW-_6XBoUpE7vpmoR3ztO&index=23 -
Website getting non responsive in next js
I'm developing an ecommerce website in next.js and django. The problem I'm facing is that sometimes the website is getting non responsive meaning it freezes the whole website and eventually I have to close the tab and start over. I have checked my code and went through several tutorials but didn't got any solution. The problem is not related to any single page or block of code. If anyone have faced any similar situation then please help me. Thanks in advance. -
Data not rendering from django database to html
Data from database to html is not rendering. The static data is rendering but unfortunately the database data is not rendering no error is comming and page is alo rendering but data is not rendering from databse to the page Html doc {% load static %} {% block title %} All Tractors {% endblock %} {% block content%} <section id="all_events"> <h1>All Tractors</h1> <h1>{{posts.implimentaion}} hi</h1> <br> <ul> {% for posts in post %} {% include "tractor/includes/singlePost.html" %} {% endfor %} </ul> </section> {% endblock %} Vews.py from django import forms from django.contrib.auth.models import User from django.shortcuts import render, redirect from .models import Post, Farmer # Create your views here. from django.http import HttpResponseRedirect # Create your views here. def starting_page(request): return render(request,"tractor/index.html") def posts(request): qs = Post.objects.all() context = {"posts":qs} return render(request,"tractor/all-post.html",context)``` -
Serializer with Foreign Keys, how to handle frontend view and backend queries?
I'm new to Django Rest Framework and I'm trying to understand how to handle the serializer both for frontend view and backend queries. I'll try to explain it better. I have these serializers: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', ) class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('name', ) class PostSerializer(serializers.ModelSerializer): author = AuthorSerializer(many=False, read_only=True) category = CategorySerializer(many=False, read_only=True) class Meta: model = Post fields = ('category', 'id', 'title', 'image', 'slug', 'author', 'excerpt', 'content', 'status', 'published') When I retrieve a post it looks like this: { "category": { "name": "django" }, "id": 2, "title": "Learn Django - Class-Based Permission Checks", "image": "http://localhost:8000/media/posts/laptop_SWf7fkV.jpg", "slug": "learn-django-class-based-permission-checks", "author": { "username": "admin" }, "excerpt": "Sed ut quam quis tellus pulvinar maximus. Nulla sodales, felis sed interdum lobortis, mi turpis dictum libero, at imperdiet justo eros a sem. Etiam et laoreet eros, quis gravida neque. Pellentesque vitae sollicitudin erat. Donec faucibus quis diam vitae pellentesque. Proin interdum justo vitae magna pretium egestas. Morbi tortor tortor, vestibulum a sagittis non, vestibulum at dolor. Etiam vulputate bibendum elit, id fermentum dui laoreet a. In ac porttitor lectus, eget tempor massa. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac … -
How to a call a REST API from a button
I'm a noob with html and django rest. In my router.py I declare my 'route' for "rest/v2" url: router.register(r"export/file/<int:id>/csv", views.IncomingFileExportViewSet, basename="ext-incomingfile-export") What I want to do is to call methods that are in the viewSet when a user press the button in the interface. Is it possible to that from html code or there is a better way? html (the button is export-csv): <div class="dropdown"> <button class="btn btn-outline-primary btn-export" aria-expanded="false" data-toggle="dropdown" aria-haspopup="true" > {% translate "Download" %} </button> <div role="menu" class="dropdown-menu"> <button id="export-csv" class="dropdown-item" type="button">{% translate "csv" %}</button> </div> </div> In another post on SO I read that it is possible using ajax, but I don't understand what should i write. -
Add annotation to all Django ORM queries that go through a model
The Django AbstractUser has fields for first_name and last_name, and get_full_name method. If I wanted to filter Users based on a search of their full name, I can add a custom model manager for the User, that has a method something like this: def filter(self, *args, **kwargs): queryset = super().get_queryset() if any(key for key in kwargs if key.startswith('full_name')): queryset = queryset.annotate( full_name=Concat(models.F('first_name'), models.Value(' '), models.F('last_name')) ) return queryset.filter(*args, **kwargs) Meaning I can do things like: User.objects.filter(full_name='Foo Bar') User.objects.filter(full_name__icontains='foo b') ... etc But of course this will only work when directly filtering Users above. If you have Post objects that are FK'd to a User, then you get this: Post.objects.filter(user__full_name='Foo Bar') ... FieldError: Related Field got invalid lookup: full_name So the question is, is there a way (without modifying all models to have custom managers), to allow Django to always recognise a given term (in this case 'full_name') on all joins to a given model's table, and annotate the necessary value so it can be filtered on? Note: I'm aware I could of course add full_name as a field on the user, and try to ensure that it's always up to date, but I'm specifically trying not to add this denormalised … -
ModelMultipleChoiceField field returning no value
How do i retrieve starred_by users by typing name in Django-admin, currently i am getting none class DocumentForm(forms.ModelForm): model = Document starred_by = forms.ModelMultipleChoiceField(queryset=User.objects.all()) class Meta: widgets = { 'created_by': AutocompleteSelect( Document._meta.get_field('created_by').remote_field, admin.site, attrs={'data-dropdown-auto-width': 'true'} ), 'organisation': AutocompleteSelect( Document._meta.get_field('created_by').remote_field, admin.site, attrs={'data-dropdown-auto-width': 'true'} ), 'starred_by':AutocompleteSelectMultiple( Document._meta.get_field('starred_by').remote_field, admin.site, attrs={'data-dropdown-auto-width': 'true'} ) } -
Django CSP Allow iframe from domain without having to set CSP for everything else
I need to allow another domain to embed my website in an iframe. I can use Django CSP to achieve this by setting the following, assuming that example.com is the domain that will be hosting the iframe of my website. CSP_FRAME_ANCESTORS = ("'self'", 'example.com') I would like Django to operate as it does out of the box, which is without CSP (correct me if I'm wrong). In this case, how could I achieve this with my CSP configuration? I currently have this, but it doesn't catch everything, and I'm not sure if it's less secure as Django out of the box, or the same. CSP_DEFAULT_SRC = ("'self'", '*') CSP_FRAME_ANCESTORS = ("'self'", 'example.com') Is this the same as how django operates by default, or have I made my application less secure by configuring it this way? -
ManyToMany django field not working, not taking any input in POST request?
I have 2 models - Module and Room. A module can have zero or multiple rooms and a room can be added into multiple modules. So, there is a simple many to many relationship between them. But when I define it in my module/models.py file, it is not taking any input as 'rooms'. here are my files - module/model.py - class Module(models.Model): module_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() rooms = models.ManyToManyField(Rooms) rooms/model.py - class Rooms(models.Model): room_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() level = models.CharField(max_length=100) is_deleted = models.BooleanField(default=False) module/serializers.py - class ModuleSerializer(serializers.ModelSerializer): rooms = RoomSerializer(read_only=True, many=True) class Meta: model = Module fields = "__all__" module/views.py - class add_module(APIView): def post(self, request, format=None): module_serializer = ModuleSerializer(data=request.data) if module_serializer.is_valid(): module_serializer.save() return Response(module_serializer.data['module_id'], status = status.HTTP_201_CREATED) return Response(module_serializer.errors, status = status.HTTP_400_BAD_REQUEST) POST request body for creating a module in POSTMAN - { "rooms": [ { "room_id": 2, "title": "4", "desc": "22", "level": "2", } ], "title": "4", "desc": "22", } With this request, module is being created, but no room is getting added in it. Can someone tell me why my rooms ar not getting added while creating modules? -
How can I read a file from ajax call in Django?
I'm working in Django. I need to upload a txt file and print its content in a table. I've tried many things but none of them work. Someone recommended that I just print the table in an ajax call, but it's not working. Here's what I'm trying: I'm showing a form to upload the file: class UploadFileForm(forms.Form): file = forms.FileField(label = "File:") I'm returning the form in a view: def upload(request): form = UploadFileForm() return render(request, 'upload.html', {'form': form}) I'm printing the form in the template: <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} </form> Then I have a button to confirm the upload: <button id="upload">Upload file</button> And here's where I try to print the table in a fetch, which is not working: var upload = document.getElementById("upload"); upload.addEventListener("click", function(){ const url = "{% url 'table' %}"; fetch(url, {method:'POST'}).then(response => response.json()).then(function(data){ var table = document.getElementById('table'); tableRow1.innerHTML = data.tableHTML; }) }) The url 'table' goes to this function: def table(request): data = file_to_HTML(request.FILES['file']) json_response = {"tableHTML":data} return JsonResponse(json_response) The problem here is that the table isn't printed at all and I get the following error: Internal Server Error: /table/ Traceback (most recent call last): File "C:\Users\Daniel\miniconda3\envs\env1\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__ list_ …