Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating model for unordered list in Django
What is the best approach to create a model field in Django, so that in template, I can iterate over its objects as: <ul> {% for item in ModelName.fieldname %} <li>{{ item }}</li> {% endfor %} </ul> so It output something like, lets say: <h1>Apple Products</h1> <ul> <li>Ipod</li> <li>Apple</li> <li>Ipod mini</li> <li>Display XDR</li> <li>Macbook Pro</li> </ul> My thoughts: Create a separate model and then reference it as foreign key to parent model. create a CharField and separate each list item with comma, then create a function; return a list and loop over list of separated items by comma. Kindly share your idea, what is better approach and professional way to do this. Thank you. -
Add extra field and value to django query set
Hi I am doing a query like user_list = Myuser.objects.filter(status=active) now I want to add a new filed matching_percentage to a user who query it , Like want to show how much it matches to your profile. Now I searched annotate function but till now I found that you cant assign a custom calculated value to new filed . So Is there any way to assign to a filed int values to show how much it matches my profile on run time by a algorithm ? -
unable to write on salesforce via heroku connect
I am using Django library called djagno-heroku-connect And I have connected my hc_connect model to the salesforce table, but I am unable to write data to Salesforce, but I am able to write data on Postgres, how can I do this? -
Django freeze after launch celery .delay. how to fix?
Run simple task to print string, and it freezing total without any error, everything is installed. celery launched, redis working, when it run delay celery app nothing print. celery.py from __future__ import absolute_import import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings.local') from django.conf import settings from celery import Celery app = Celery('src') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print("Request: {0!r}".format(self.request)) my tasks.py import os import datetime from celery import Celery from celery import shared_task @shared_task def testfunc(): print('EKHASGBDJHGASd') return False my launch that func in views testfunc.delay() Linux mint 19.1 -
How to localize django-tinymce and show it in form?
I am using tinymce to Article model. First problem, it shows it only in the admin page and not in article creation form. Second, I don't know how to localize it. I use this in settings.py: TINYMCE_DEFAULT_CONFIG = { 'language': 'sv_SE', } text field in Article in models: text = HTMLField('body',max_length=4000) Article creation form in forms.py: class ArticleCreationForm(forms.ModelForm): # specify the name of model to use class Meta: model = Article fields = "__all__" exclude = ['votes', 'author'] -
I want to update the model I created. However, I want to do this through the id of the model
I want to update my model according to the id number. how can I do that? I can update the model but I want to do this via id and another problem i have is i want only the creator to be able to update the model Model.py class Advertise(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=100, verbose_name="ilan başlığı") description = models.TextField(max_length=500, verbose_name="ilan açıklaması") price = models.PositiveIntegerField(default=0, verbose_name="Fiyat") square_meter = models.PositiveIntegerField(default=0, verbose_name="Metrekaresi") number_of_rooms = models.PositiveIntegerField(choices=NumberOfRoomsChoices.CHOICES, verbose_name="Oda sayısı") building_age = models.PositiveIntegerField(choices=NumberOfBuildingAgeChoices.CHOICES, verbose_name="Bina Yaşı") floor = models.PositiveIntegerField(choices=NumberOfFloorChoices.FLOOR_CHOICES, verbose_name="Bulunduğu Kat") serializer## class AdvertiseMainSerializer(ModelSerializer): class Meta: model = Advertise fields = '__all__' view.py## class UpdateAdvertiseData(UpdateAPIView): serializer_class = AdvertiseMainSerializer queryset = Advertise.objects.all() def perform_create(self, serializer): serializer.save(owner=self.request.user) urls.py## url(r'^UpdateAdvertiseData/(?P<pk>[-\w]+)/$', UpdateAdvertiseData.as_view()), -
Error sub-select returns 4 columns - expected 1 when saving data to database
I am trying to submit the django form which takes automatic username from input field and takes a checklist of names. When I submit form it gives me error sub-select returns 4 columns - expected 1 This is my function from views.py def weekly(request): context = '' weekly_form = WeeklyForm() daily_form = DailyForm() context = {'weekly_form': weekly_form, 'daily_form': daily_form} # Weekly Report Code to execute on submit if request.method == 'POST' and 'weekly' in request.POST: form = WeeklyForm(request.POST) print("This line is printed in weekly") if form.is_valid(): tname1 = request.POST.get('teachers') data = form.cleaned_data print (data) print("This line is printed 1") report = wreport(tname = tname1, sname = data['sname'], fdate = data['date'], objective = data['objective'], tplan = data['target'], how = data['how'], material = data['material'], extra = data['support']) report.save() messages.success(request, "Your report was submitted Successfully.") else: print(form.errors) This is my Database model class wreport(models.Model): _id = models.AutoField tname = models.CharField(max_length = 255, default = "") sname = models.CharField(max_length = 255, default = "") classes = models.CharField(max_length = 255, default = "") fdate = models.DateField() objective = models.CharField(max_length = 255) tplan = models.CharField(max_length = 512) how = models.CharField(max_length = 255) material = models.CharField(max_length = 512) extra = models.CharField(max_length = 255) This is my Form … -
Minimize repeat phrases "blank=True, null=True" in django
It's sadly for me to write same phrases again and again in python code, so I'm looking for ways to improve it. Do you know any way to minimize this phrases? Maybe something like with blank=True as bt and null=True as nt ? -
How can I create a Django EmailMessage from a MIME string or python email?
Is there a method to create a django EmailMessage object from a string, like python's email.message_from_string()? I need to forward a mail I get as a MIME string from an API. I replaced some headers like this: import email mail = email.message_from_string(email_string_from_api, policy=email.policy.default) mail.replace_header("From", "replaced_from@example.com") Now I want to convert the python email object (or the string) to a django EmailMessage, how can I do this? -
Django form returns method as GET instead of POST
I've set method='POST' but print(request.method) in my view prints GET and I don't know why, so my button won't work and save the data, I have tried everything i know but my code doesn't get fix This my template where I have set method as POST in form tag and also I have set action of form with the url, I have also set formmethod as POST in button tag: <div class="row"> <div class="col-12"> <div class="card m-b-30"> <div class="card-body"> <form action="{% url 'create_production' %}" method="POST"> {% csrf_token %} <div class="row"> <div class="col-lg-4"> <div class="p-20"> <div class="form-group"> <label>تاریخ</label> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text cursor-pointer" id="tdate"><i class="fa fa-calendar" aria-hidden="true"></i></span> </div> {{ form.date }} </div> </div> <div class="form-group"> <label>نام شرکت</label> {{ form.comName }} </div> <div class="form-group"> <label></label> {{ form.comId }} </div> <div class="form-group"> <label>نام محصول</label> {{ form.prodName }} </div> <div class="form-group"> <label></label> {{ form.prodId }} </div> </div> </div> <div class="col-lg-4"> <div class="p-20"> <div class="form-group"> <label></label> {{ form.gradeId }} </div> <div class="form-group"> <label>نام گرید</label> {{ form.gradeName }} </div> <div class="form-group"> <label>نوع گرید</label> {{ form.gradeType }} </div> <div class="form-group"> <label>تولید</label> {{ form.qty }} </div> </div> </div> <div class="col-lg-4"> <div class="p-20"> <div class="form-group"> <label>ظرفیت</label> {{ form.cap }} </div> <div class="form-group"> <label>ظرفیت طراحی</label> {{ form.designCap }} … -
Display user submitted values from django forms in the same HTML page
I wanted to display user submitted values in the same HTML page. I'm able to display those values but it's comes in python dictionary format. I'm getting the result : 'first_name': 'Tom', 'last_name': 'Hanks'}, Is there any way to display only First Name and Last Name separately. views.py from django.shortcuts import render from django import forms class DbNames(forms.Form): first_name = forms.CharField(label="First Name") last_name = forms.CharField(label="Last Name") def index(request): return render(request, "emp/index.html") def form_gen(request): form = DbNames() if request.method == "POST": form = DbNames(request.POST) if form.is_valid(): return render(request, "emp/users.html", { "form_data": form.cleaned_data }) else: print('ERROR') return render(request, "emp/users.html", { "result": form }) -
How to change the path in the change page of the admin django panel
All the files that I upload in the django admin panel are stored in a FTP server, no files are stored locally. An example of how the change page looks after the file has been uploaded I'd like to know how to change that circled href, so that when I click on it the path corresponds to the ftp path + the uploaded file's name. So it currently links to "http://127.0.0.1:8000/admin/basic_app/software/6/change/profile_pics/file_name", but it should link to something like "ftp://:@:/folder/file_name", so that when it's clicked it opens the file on the FTP server. Is this solvable by altering a url path somewhere, or do I have to do a template override of these pages? -
Change status of a record in sql database depending on deadline date
I have this project in Django where I need to change the status of the particular record in the database depending on the particular deadline. I am using Mysql as database. what is the best way to achieve this?. Example : I have a database of student's project submission. By default status is 'on-time' of every student field but if the project is not submitted till the date (date stored in the database ). status of the record would be changed to 'Late Submission' in the database. what is the best way to achieve this functionality? With SQL, python or javascript? -
Form(prefix=) and Race Conditions
As a small learning project, I am using Form prefix to submit two separate forms (same Model) as a one-page form. The model Account has a field account_number that increments after each model save. The initial value either 1 or user-defined. My issue is that my form2 doesn't receive the correct value. I have been trying to use F() expressions and request_from_db() but I'm not sure if I am implementing them properly. I have tried using a call back on the default value in the account_number field (below) but I can see that the default account_number on Form2 is the same as Form1. It does change after saving, but If I open two browsers tabs of the form page before I submit the first page, the account_numbers aren't unique. My Account model.py def account_number_increment(): last_number = Account.objects.all().order_by("account_number").last() if last_number: print("before db refresh", last_number.account_number) last_number.refresh_from_db() print("after db", last_number.account_number) start_from = AccountNumber.start_from acc_number = '1' if start_from: while Account.objects.all().filter(account_number=start_from).exists(): acc_number_start = int(last_number.account_number) + 1 print("acc # from start from", acc_number_start) return str(acc_number_start) if last_number: while Account.objects.all().filter(account_number=last_number.account_number).exists(): new_acc_number = int(last_number.account_number) + 1 print("acc # from last number", new_acc_number) return str(new_acc_number) if not last_number or not start_from: return acc_number class Account(models.Model): uuid = models.UUIDField(primary_key=True, … -
I am trying to test a relationship with Inspection and Defect using Django and got an error in tests.py
I am trying to do a fun project that relates Inspections and Defects. The error I got was Inspection() got an unexpected keyword argument partNum. Here is my urls.py. from django.urls import reverse from django.urls import resolve from django.test import TestCase from .views import home,inspection_defects from .models import Inspection # Create your tests here. class HomeTests(TestCase): def test_home_view_status_code(self): url = reverse('home') response = self.client.get(url) self.assertEquals(response.status_code, 200) def test_home_url_resolves_home_view(self): view = resolve('/') self.assertEquals(view.func, home) class InspectionDefectTest(TestCase): def setUp(self): Inspection.objects.create(workOrderNum='312456',partNum='SD33345100-AQ1',customerName='TERRA Inc.',qtyInspected=10,qtyRejected=2) def test_inspection_defects_view_success_status_code(self): url = reverse('inspection_defects', kwargs={'pk': 1}) response = self.client.get(url) self.assertEquals(response.status_code, 200) Here is my urls.py file. from django.conf.urls import url from django.contrib import admin from finalreports import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^inspections/(?P<pk>\d+)/$', views.inspection_defects, name='inspection_defects'), url(r'^admin/', admin.site.urls), ] -
How to overwrite delete method in generics class (DRF)
I have to models: Wallet and Transaction and a Wallet have many Transactions. I want to return the amount of money for the Wallet that transaction belong to if I delete a transaction. But I don't know how to do that. Bellow is my class view class TransactionDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Transaction.objects.all() serializer_class = TransactionSerializer name = 'transaction-detail' Thank you! -
how to update database in django
I want to update my database in django from html page not django form. then i tried this and i got this error. Here is the view def contact(request): if request.method=="POST": email = request.POST["e_mail"] name = request.POST["name"] phone = request.POST["phone"] message = request.POST["message"] new_contact = Contact() new_contact.email = email new_contact.name = name new_contact.phone = phone new_contact.message = message new_contact.save() return render(request, 'contact.html', {}) and i got error butwhen i did with one mapping in a page it worked but now it didn't work. -
use two select tag to filter data in django
hello friend I am making notes sharing website. I have one problem with the following code. I want to use two select tags in my page so that I can filter data from the database. but I want both select tags to work dynamically. the first tag of semester load with the page and when I select the option it transfers to view and I have applied a filter in the view file so from the view part return subject data to the next tag(subject tag). the code is given below. main.html <form action="" method="POST"> {% csrf_token %} <select name="semester" id="semester" onchange="this.form.submit()"> <option value="">Select Semester</option> {%for i in semester %} <option value="{{i.id}}">{{i.Sem}}</option> {%endfor%} </select> </form> <form> <select name="subject" id="subject"> <option value="">Select Subject</option> {%for i in subject %} <option value="{{i.id}}">{{i.Subject}}</option> {%endfor %} </select> <noscript><input type="submit" value="Submit"></noscript> </form> view.py def main(request): semester = Semester.objects.all() subjects = Subject.objects.all() data = {} if request.method == "POST": a = request.POST.get("semester") if a != "": subjects = Subject.objects.filter(Semester=a) print(subjects.values()) data = {'subjects':subjects, 'semester':semester} return render(request,'main.html',data) -
How to convert zipfile.ZipExtFile to acceptable type for pygltflib.GLTF2.load() argument?
I have a Django ViewSet class that has a post method. With said view class I registered an API endpoint. The API endpoint accepts a zip file in the Body's form-data when sending a POST request. The zip file contains several GLB files in it. Each GLB file may have 1-to-many Mesh. I need to get all the Mesh names from each GLB file. To load a GLB file I want to use glb_file = GLTF2().load(filename). To get all the meshes I supposed could do meshes = glb_file.meshes. Here's some part of my views.py: from rest_framework.viewsets import ViewSet from rest_framework.response import Response from rest_framework import permissions from django.core.files.base import ContentFile from zipfile import ZipFile from pathlib import Path from pygltflib import GLTF2 from .models import * class AssetCreateZipView(ViewSet): permission_classes = [permissions.IsAuthenticated] def list(self, request): return Response('Make post request by uploading a zip file containing asset files.') def post(self, request): # form-data key = zip. request_data = request.FILES['zip'] with ZipFile(request_data, 'r') as zip_obj: zip_name = Path(zip_obj.filename).stem # traverse through assets. for name in zip_obj.namelist(): with zip_obj.open(name, 'r') as file: product = Product.objects.get(name__iexact=zip_name) glb_file = GLTF2().load(file) # the error occurred here. meshes = glb_file.meshes # for mesh in meshes, Mesh.objects.create(product=product, name=mesh) *** … -
Automatic selection of user when we create post in django restframework
When I create a model, how do I ensure that the user can be selected as the user I am logged in to? view.py## class advertise(CreateAPIView): serializer_class = AdvertiseMainSerializer queryset = Advertise.objects.all() serializer py## class AdvertiseMainSerializer(ModelSerializer): class Meta: model = Advertise fields = '__all__' -
I CANT IMPORT THE VIEWS MODULE FOR DJANGO
Im just starting to work with Django in python, and whenever i try to import the views module i get this import error : ImportError: attempted relative import with no known parent package from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ] -
Can I call receiver function without signal call?
I have receiver function @receiver(paid) def add_transaction(sender, payment_uid, **kwargs): do some stuff which is called after payment. Can I call it also explicit, without signal? -
Read and retrieve data from qr code zxing in django
I am using the zxing package to scan some QR codes in my Django project. Now I would like to send the QR code data to my backend to use it but I get lost. Enlighten me, please. -
how to make login in my django website from login of any other website login page using okta oauth2
There is a login button in my website. when a user click on that button, they should be redirect to some other website login page or we can say server. after login that should be redirect to my website page. i have client id, client secret, redirect url, logout url. can anyone tell me how to do that with okta oauth2 in django Thanks. -
Django-Dialogflow-GoogleVisionAPI cannot load static files of Django
I am trying to complete the official google demo about Dialogflow. https://github.com/priyankavergadia/Django-Dialogflow-GoogleVisionAPI Home.html cannot load static files, and I cannot figure out why. Please help! I am continuously getting the error message like; GET file:///User/Django-Dialogflow-GoogleVisionAPI/chat/templates/%7B%%20static%20'css/bootstrap.css'%20%%7D net::ERR_FILE_NOT_FOUND and I tried to search for the similar error, but not enough resources can be found on the internet. {% load staticfiles %} <html> <head> <title>Django Dialogflow</title> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"/> <link rel="stylesheet" href="{% static 'css/custom.css' %}"/> </head> <body> <div class="container"> <div class="page-header text-center"> <h1>Dialogflow</h1> </div> <div class="row"> <div class="col-xs-6 col-xs-offset-3"> <ul class="list-group js-chat-log"> </ul> <div class="input-group input-group-lg"> <input type="text" class="form-control js-text" placeholder="Type something to begin..."/> <span class="input-group-btn"> <button class="btn btn-primary js-say">Submit</button> </span> </div> <input type="file" class="custom-file-input" name="file" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01"> </div> </div> </div> <script src="{% static 'js/jquery.js' %}"></script> <script src="{% static 'js/js.cookie.js' %}"></script> <script src="{% static 'js/bootstrap.js' %}"></script> <script> var $chatlog = $('.js-chat-log'); var $input = $('.js-text'); var $sayButton = $('.js-say'); var dialogflowUrl = '{% url "index" %}'; var csrftoken = Cookies.get('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); var file_length_bool = true; // helper method to create the …