Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Template not showing data (is blank) fetched from sqlite using view function by passing a parameter
I have implemented a feature where there is a view button next to each event row fetched from db and clicking on this view it is sending the id of event to url which then sends it to the view to fetch the filtered data from sqlite but it is not showing the data template.html <td><a href="{% url 'event' eid=ev.id %}">View</a></td> urls.py path('<int:eid>', views.event_det, name='event'), views.py def event_det(request, eid): data = Event.objects.filter(id=eid) return render(request, 'event_details.html', {'event': data}) template.html to show the fetched output {% for ev in event %} <div class="card mb-12"> <div class="row no-gutters"> <div class="col-md-12"> <img src="{% static 'face_detector/datasets/9187/color-1.png' %}" class="card-img" alt="..."> </div> <div class="col-md-12"> <div class="card-body"> <h2 class="card-title">{{ ev.name }}</h2> <p class="card-text">{{ ev.description }}</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> </div> ... -
How to send the formdata from the ajax to Django view in PUT request?
I am sending the ajax call to the python django view(no rest framework) and want to perform the update operation in django using PUT request. This update operation involved files too so I don't know to do PUT operation for files. I have performed GET, POST, DELETE operations but not understanding the PUT. I am sending the formdata object from the ajax. Thanks in advance!! -
How to add js media file in ModelAdmin class
I have created ModelAdmin class inside I have defined media class for js file but when I am running my admin site I am not getting any response what I want to see. here is my app admin.py from django.contrib import admin from .models import Applications, Country, State # modeladmin have several attribute used to coustmize model view in admin dashboard class ApplicationsAdmin(admin.ModelAdmin): fields = ('name', 'country', 'state', 'city') class Media: js = 'asd.js' admin.site.register(Applications, ApplicationsAdmin) asd.js $(document).ready(function(){ $("#id_country").change(function(){ country_id = $(this).val(); var url = $("#ApplicationForm").attr("data-states-url"); console.log((country_id)); var countryId = country_id $.ajax({ url: url, data: { 'country': countryId}, success: function (data) { <!-- console.log(data)--> $("#id_state").html(data); } }); }); }); models.py class Applications(models.Model): country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=True) state = models.ForeignKey(State, on_delete=models.SET_NULL, null=True, blank=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=30) is there any other way to do it or am I doing something wrong? -
Generate PDF in django rest framework
I have a serializer class. I have new order form in the frontend,now I want to create invoice from the input in the frontend.how can I achieve this with react and Django rest framework -
How to use the variable value inside <img src=""> in django template?
I am not able to read the django variable value inside my img src tag . It is reading the variable name likewise it is not dynamically. <div class="col-md-4"> //ERROR IS HERE <img src="{% static 'face_detector/datasets/{{ del.dataset_id }}/color-1.png' %}" class="card-img" alt="..."> </div> <div class="col-md-8"> <div class="card-body"> <h2 class="card-title">{{ del.first_name }} {{ del.last_name }}</h2> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> </div> i want to access the value of "del.dataset_id" in my image src path -
How to validate model field using validator method in Django
I want to validate email while saving an object through API. I'm using model validate but it's not working while saving Invitation object through API, It's working only when we creating objects through the admin panel. models.py def validate_email(value): if "@gmail.com" in value: return value else: raise ValidationError("This field accepts mail id of google only") class Invitation(models.Model): email = models.EmailField(validators=[validate_email]) -
Django model form with related objects how to save and edit
I am developing an application which have related models like Trip can have multiple Loads. So how can i design the create form to acheave the desired functionality. i know formset can be used to acheave the functionality but i want custom functionality like: User can create new load while creating trip, the added loads will be show in a html table within the form with edit and delete functionality being on the Trip create page. I have acheaved the functionality using two ways but i am looking for a neater and cleaner approach. what i have done so far was: I added the Loads using ajax and retreaved the saved load's id and store in a hidden field, when submitting the main Trip's form i create object for Trip and retreave Loads's object using id and map that Trip id in the Load's object. I have keep Loads data in the javascript objects and allow user to perform add edit delete Loads without going to the database, once user submit the main Trip form i post Loads's data and create objects and save in the database. Please let me know if anybody have done this type of work and … -
How to send variable from Template to Path and use it in a related view function?
Basically, I have list of persons and i want to implement a details feature for each person so that whenever i click on view besides the particular person row in the table it should send the person's id to the path in the urls.py which then will call the respective view function. I ve tried something and adding the code below but its not working. thanks for reading. template.html <tbody> {% for del in delegates %} <tr> <td>{{ del.id }}</td> <td>{{ del.first_name }} {{ del.last_name }}</td> <td>{{ del.email }}</td> <td>{{ del.phone }}</td> <td>{{ del.company }}</td> <td>{{ del.designation }}</td> <td>{{ del.address }}</td> <td>{{ del.city }} ({{ del.pincode }})</td> //MY VIEW DETAIL BUTTON <td><a href="{% url 'delegate:delegate_details' del_id=del.dataset_id %}">View</a></td> </tr> {% endfor %} </tbody> urls.py from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('', views.index), path('view-delegates', views.view_delegates), path('delegate-details', views.delegate_det), url(r'^delegate/(?P<del_id>[0-9]+)$', views.delegate_det, name='delegate'), ] views.py def delegate_det(request, dataset_id): # data = Delegate.objects.all() data = Delegate.objects.filter(dataset_id=dataset_id) return render(request, 'delegate_details.html', {'delegate': data}) P.S: I am a beginner in Python -
ListSerializer for json
I want to return the json like this, {"texts":[ "string1 "string2" "string3" ]} One simple index texts has list my Object is here class Task(object): def __init__(self, texts, created=None): self.texts = texts self.created = created or datetime.now() The problem is serializer, because texts is list so I need to use ListSerializer So I made this, but after serialized texts field is empty. class TextSerializer(serializers.Serializer): serializers.CharField(max_length=200) // it's something wrong....?? class TaskSerializer(serializers.Serializer): texts = TextSerializer(many=True) created = serializers.DateTimeField() -
How to write an excel file which has dictionary keys as column name and dictionary values as column values?
I have a dictionary as follows: {'tarih': '01.02.2019', '4980': 1.1517482514, '2738': 0.9999999999999999, '0208': 1.0102518747365854} I want ot write an excel file like: tarih 4980 2738 0208 // dictionary keys as column name 01.02.2019 1.1517482514 0.9999999999999999 1.0102518747365854 // dict values as value -
How to access the dynamically generated tuple in Python?
I have created a tuple for django model choices dynamically. The choices look like this [('cash', 'Pay via cash'), ('internet_banking', 'Pay via internet banking'), ('C2P', 'Pay via Credit Card')] Created it dynamically because the generated options depend on some conditions. Number and Type of available payment options depend on certain conditions. Now, I want to access this dynamically generated choices throughout the code, like if selected choices is cash, then do this, otherwise do something else. Unable to use something like this PAYMENT_METHOD_CHOICES.cash get error Tuple object has no attribute cash -
How can i filter the data in django?
I used pagination to my view and can search data with subject_name keywords but now i want search them according to their subject duration in dropdown format. view.py @login_required def servicesview(request): services = ServicesData.objects.all() key = request.GET.get("search_key", "") if key: services = ServicesData.objects.filter(subject_name__icontains=key) page = request.GET.get('page', 1) paginator = Paginator(services, 2) try: services = paginator.page(page) except PageNotAnInteger: services = paginator.page(1) except EmptyPage: services = paginator.page(paginator.num_pages) return render(request, 'services.html', {'services': services, 'key': key}) services.html <form> <input type="text" name="search_key" value="{{key}}" placeholder="Search.."> <input type="submit" value="Submit"> </form> My page is something like below: Reality But i want something like below for subject_duration: What i want Please someone help -
Implement messaging feature between admin and user using django-postman?
I am newbie to django I am trying to implement a messaging feature in my django where the admin and user need to chat with each other like a thread for that i had downloaded the django-postman from bitbucket and in my project installed apps I had included postman even I am getting the import error of some packages like six,python_2_unicode_compatible should I need to download any other packages for getting this requirement be done in my project If yes can you please say me what are those? -
Django Learning
I have started learning Django.I am following a tutorial series. Here after some tutorials they started class-based views.Should I give more focus on Function-based view or Class-based view for better learning.Thank you. -
How do i this query in Django views?
"SELECT Password from user_registration_data where Email='user@email.com' " My models.py code is: class user_registration_data(models.Model): name=models.CharField(max_length=100, blank=False) Address=models.CharField(max_length=100, blank=False) Password=models.CharField(max_length=100, blank=False) Email=models.EmailField(max_length=250, blank=False) -
Object of type UserForm is not JSON serializable
I am running a django application . I have an error : TypeError: Object of type UserForm is not JSON serializable Below is the code: forms.py: from django import forms from .models import Profile from django.contrib.auth.models import User class UserForm(forms.Form): username=forms.CharField(widget=forms.PasswordInput) password=forms.CharField(widget=forms.PasswordInput) class Meta(): model=User fields=('username','password') views.py: def signup(request): registered=False failed_ref=False wrong_ref=False if request.method=='POST': user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() user_form=UserForm() return JsonResponse({'user_form':user_form,'registered':registered, 'failed_ref':failed_ref,'wrong_ref':wrong_ref}) How to make this form JSON serializable? -
When I run the Python code in Visual Studio Code Editor below, I get
def post(self, request, *args, **kwargs): post_data = request.data task_id = post_data.get("task_id") head = post_data.get("comment_head") value = post_data.get("comment_description") code = post_data.get("code") task = entity_Task(task_id=task_id) if task and head and value: try: if code and code == DELAY_FLAG_CODE: entity_Comment.add_comment_flag_delay( user=user, task_id=task_id, value=collection_feedback) else: comment = entity_Comment.add_comment_with_task_id( user=request.user, task_id=task_id, head=head, value=value) return JSONResponse({'code': 200, 'response': {"status": "Comment Saved"}}) except Exception as e: xprint(e, traceback.format_exc()) return JSONResponse({'code': 500, 'response': {"error": str(e)}}); return JSONResponse({'code':200,'response':'Data Insufficient'}) after running this code in vscode editor I get below error IndentationError: unindent does not match any outer indentation level. -
API without model on django rest framework
I want to make two API entries, one is with model(genre) and the another is without model(task). But I can access only http://127.0.0.1:8000/api/genres but not http://127.0.0.1:8000/api/tasks On api toppage shows only genres where am I wrong? These are codes below. in urls.py router = routers.DefaultRouter() router.register(r'genres', GenreViewSet) router.register(r'tasks', TaskView, basename='api') in views.py class GenreViewSet(viewsets.ModelViewSet): queryset = Genre.objects.all() serializer_class = GenreSerializer class TaskView(views.APIView): @classmethod def get_extra_actions(cls): return [] def get(self, request): yourdata= [{"likes": 10, "comments": 0}, {"likes": 4, "comments": 23}] results = TaskSerializer(yourdata, many=True).data return Response(results) in serializer.py class GenreSerializer(serializers.ModelSerializer): class Meta: model = Genre fields = ('id','name') class TaskSerializer(serializers.Serializer): comments = serializers.IntegerField() likes = serializers.IntegerField() -
Django build tables dynamically with filters
I am looking to build tables on our business website dynamically. At the moment we have multiple pages with tables and filters that allow for search but I have to go in and construct a table for each of them based on the data that should be displayed. I was hoping to find a way to use one main template file that can encompass most instances for creating a new page. The difficulty I am having is trying to loop through the data and place it in the correct cell. (Some code has been removed for readability.) View: def newDynamicView(request): jobs = Jobstable.objects.all().order_by('-index') filter = NewFilter(data, queryset = jobs) fields_model = filter._meta.fields fields_text = [] for field in fields_model: fields_text.append(FIELD_NAME_TEXT[field]) return render(request, 'MYSQLViewer/olivia.html', {'filter': filter, 'fields_model': fields_model, 'fields_display': fields_text}) Current Template (Relevant info): <div class="table-responsive"> <table id="data_table" class="table table-dark table-bordered table-responsive"> <thead class="thead-light"> {% for field in fields_display %} <th>{{field}}</th> {% endfor %} </thead> <tbody> {% for job in filter.qs %} <tr> {% for model_field in fields_model %} <td class="pt-3-half edit {{model_field}}" contenteditable="true" id="{{model_field}}-{{job.index}}">{{job.model_field}}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> From what I understand, the problem lies in this tag: {{job.model_field}} My idea was to grab the … -
Saving django instance with foreign key
I have two models Applicant and LoanRequest. Whenever an Applicant model is created, a signal is sent to a function that makes an API call. The data from the call, along with the primary key of the instance that sent the signal is saved to the LoanRequest model. When I save the LoanRequest, however, it gives the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: queues_loanrequest.dealer_id_id Here's my code: class Applicant(models.Model): app_id = models.CharField(max_length=100) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.first_name + " " + self.last_name class LoanRequest(models.Model): loan_request_id = models.CharField(max_length=100) app_id = models.ForeignKey(Applicant, on_delete=models.CASCADE) FICO_score = models.CharField(max_length=100) income_risk_score = models.CharField(max_length=100) DTI = models.CharField(max_length=100) date_requested = models.DateTimeField(default=timezone.now) loan_request_status = models.CharField(max_length=100,blank=True) dealer_id = models.ForeignKey(Dealer, on_delete=models.CASCADE,blank=True) def credit_check(sender, instance, **kwargs): credit_json = get_credit(instance.pk) #credit information for applicant credit_json = json.loads(credit_json) new_request = LoanRequest.objects.create(app_id=instance, FICO_score=credit_json["ficco-score"], income_risk_score=credit_json["income-risk-score"], DTI=credit_json["DTI"]) Very new to Django, would greatly appreciate help!! -
Got some serious issue on django rest framework
I am getting error while saving data in database.Error shows something like this __init__() takes 1 positional argument but 2 were given views: class BusinessDetails(APIView): def post(self, request, *args, **kwargs): serializer = DetailSerializer(data=request.data) if serializer.is_valid(): BusinessDetails( serializer.save() ) return Response({"message": "sucess", "code": status.HTTP_201_CREATED, "details": serializer.data}) return Response({'message': 'failed', 'error': serializer.errors}) urls.py path('detail/', BusinessDetails.as_view()), -
how to find Django memory leakage
How to find memory leakage of python Django application with valgrind tool or any other way to find the python memory leakage. Please suggest me some tools to find and fix the memory leakage. -
logical bug while matching record from models in python django
models.py i copied the username from database then write it in the login form inspite of this its not matching the record and ,control moves toward except and final condition,please any one here to help improve my code as well, overall i think program is good and where is the error i am not getting the point where is error actually class UserAccountModel(models.Model): ContactEmail = models.EmailField(max_length=30) FirstName = models.CharField(max_length=30) LastName = models.CharField(max_length=40) Counrty = models.CharField(max_length=50) Phone = models.IntegerField() ChooseUserName = models.CharField(max_length=30) password = models.CharField(max_length=32) EnterCaptcha = models.CharField(max_length=4) payments = models.BooleanField(max_length=6, default=False) showsponsor = models.CharField(max_length=30, default=False) RegisteredDate = models.DateTimeField(auto_now_add=True, blank=True) ActivationOn = models.DateField(auto_now_add=False,blank=True) expiry_date = models.DateField(auto_now_add=False,blank=True) def __str__(self): return self.FirstName + ":" + self.ChooseUserName views.py def join(request): if request.method == 'POST': refrer = request.POST['showsponsor'] try: if UserAccountModel.objects.get(ChooseUserName=str(refrer)): ContactEmail=request.POST['email'] FirstName=request.POST['firstname'] LastName=request.POST['lastname'] Counrty=request.POST['country1'] Phone=request.POST['phone'] ChooseUserName=request.POST['username'] password=request.POST['password2'] EnterCaptcha=request.POST['captcha'] payments=request.POST['payment'] # referal_Name = request.POST['showsponsor'] join_save_record = UserAccountModel.objects.create(ContactEmail=ContactEmail,FirstName=FirstName,LastName=LastName,Counrty=Counrty,Phone=Phone,ChooseUserName=ChooseUserName,password=password,EnterCaptcha=EnterCaptcha, payments='True',) join_save_record.save() print(join_save_record.FirstName) namew=request.POST['showsponsor'] # session creating request.session['ChooseUserName'] = str(refrer) rerredby = request.session.get("ChooseUserName") print("session created : " + str(rerredby)) return render(request, 'payment_verify.html', {'rerredby':rerredby}) except UserAccountModel.DoesNotExist: messages.info(request, 'invalid refrer except case name contact to the right persone who did') print("denied") return redirect("/join") finally: user = authenticate(username=str(refrer)) if user is not None: ContactEmail = request.POST['email'] FirstName = request.POST['firstname'] LastName = … -
How to extract information out from event.data in django channels
Hello i have some trouble trying to extract and transfer data from my backend to my front end. Here is my code. <script type="text/javascript"> var loc = window.location var wsStart = 'ws://' if (loc.protocol == 'https'){ wsStart = 'wss://' } var endpoint = wsStart + loc.host + loc.pathname var socket = new WebSocket(endpoint) socket.onmessage = function(e){ var x = e.data; console.log("message",e); badgeCreate(); console.log(x.message); alert(x); } socket.onopen = function(e){ console.log("open",e) console.log(e.error) } socket.onerror = function(e){ console.log("error",e) } socket.onclose = function(e){ console.log("close",e) } </script> this is a relevant bit of my consumers.py: async def user_notification (self, event): close_old_connections() print('user noti gets called') await self.send_json({ 'event': 'notification', 'data': { 'event_type': 'notification', 'notification_pk': event['notification_pk'], 'link': event['link'], 'date_created': event['date_created'], 'message': event['message'], } }) print(event) This is printed on my alert box: {"event": "notification", "data": {"event_type": "notification", "notification_pk": 64, "link": "test", "date_created": "2020-01-23 05:27:08", "message": "wqe"}} Changing x=e.data to x= e.data.message results in it being undefined. Does anyone know what is happening? -
ModuleNotFoundError: No module named 'django' when deploying to Elastic Beanstalk
I have been working on a Django project locally and I finally decided to release it to AWS Elastic Beanstalk and during the deployment process I keep receiving an error saying: from django.core.wsgi import get_wsgi_application No module named 'django' I have walked through the official tutorial from AWS as well as the tutorial from the Real Python I have verified that Django is in fact installed by running pip freeze and it returns ... colorama==0.3.9 Django==2.2.9 django-celery==3.3.1 .... Also I've been working with Django extensively locally. But just to be sure I ran the following command and got this output. (.venv) $ source .venv/bin/activate (.venv) $ pip install django Requirement already satisfied: django in ./.venv/lib/python3.7/site-packages (2.2.9) Requirement already satisfied: sqlparse in ./.venv/lib/python3.7/site-packages (from django) (0.3.0) Requirement already satisfied: pytz in ./.venv/lib/python3.7/site-packages (from django) (2019.3) And when I run: (.venv) $ python Python 3.7.4 (default, Jul 9 2019, 18:13:23) [Clang 10.0.1 (clang-1001.0.46.4)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> print(django.__file__) .../code/core_web_app/.venv/lib/python3.7/site-packages/django/__init__.py Sorry if this is over kill but most of the post I have looked at have comments asking if Django is installed or saying that Django must be installed. My presumption is …