Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin widget override for all of abstract model
I have an abstract model that contains a field type that I would like to override the widget for in the admin view. Now you can't register abstract models in the admin view so I have had to override the widget for each of the models that inherit from the abstract model. This feels clunky - is there a neater way to do this? -
Time-Based Indexing in Elasticsearch in python? like daily logs date suffix index
i am developing a 3rd party tool which is fetching report data from apis, i am indexing this in elastic search using django_elasticsearch_dsl But every time i index the fetched data it overrides the previous one. one approach was mentioned in the documentation help i.e We can store index fer day with date as suffix in index name. For example: index_name = report-yyyymmdd-hhmmss How to do this in python using django_elasticsearch_dsl? What is the best practice to do this? Here is my code: class ReportDocument(Document): def prepare_labels(self, instance): if instance.labels == '--': return '' return list(map(str.strip, eval(instance.labels))) class Index: name = "report1" settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = Report fields = [ field.name for field in Report._meta.get_fields()] auto_refresh = False -
Can't serialize request.data with another function inside post method.using Post request. DRF
I'm pretty new to Django and DRF. I have a Model with Image and ForeignKey fields. class Image(models.Model): image = models.ImageField(blank=False, null=False) predicted_result = models.ForeignKey(PredictedIllness, on_delete=models.CASCADE) Serializer: class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields =['image','predicted_result'] And a view: class UploadImage(APIView): def post(self, request, format=None): serializer = ImageSerializer(data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response('Classified', status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def classify_image(self, image_file, image): image = open_image(image) pred_class, pred_idx, outputs = fastAi_learner.predict(image) print(pred_class.data.item()) return pred_class.data.item() So when I'm shooting with the POST request, everything works fine and Response: 'Classified' withStatus 201 is returned. But, what I want to do is to classify image myself, using classify_image function. def post(self, request, format=None): try: im = pilImage.open(request.data['image']) if im.load(): predicted_condition = self.classify_image(image_file=request.data['image'].name, image=request.data['image']) request.data['predicted_result'] = predicted_condition serializer = ImageSerializer(data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(1, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except IOError: return Response('problems with image', status=status.HTTP_400_BAD_REQUEST) For Some reason, When I'm shooting from Postman with exactly the same request I receive the following 400 Response: { "image": [ "Upload a valid image. The file you uploaded was either not an image or a corrupted image." ] } What can cause this error is thrown? Because I send exactly the same image. And how can … -
email field in Django only for corporate emails
Guys Is it possible in sign up form to limit email input only to corporate emails such as @bp.com @kpmg.com etc so to eliminate non-business emails such as gmail.com yahoo.com etc? So that if user insert xxx@gmail.com the form rejects and ask to insert business emails? I saw such option when i applied for master and they required for recomendation to insert business emails. I hope you got what i mean. What source you would advise to look for or what example of code you can share? If you can sharwe any would be great to have some idea. My forms.py is from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm class UserCreateForm(UserCreationForm): class Meta: fields = ('username','email','password1','password2') model = get_user_model() def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Display Name' self.fields['email'].label = 'Email Address' Any help would be appreciated. -
why the time in Django rest framework is not correct
why when I updated an entry in the database the updated time field in the model updated = models.DateTimeField(auto_now=True) is updated correctly according to timezone in my settings file but when it appeared in the Django rest Framework terminal it is shifting back 3 hours the following code is for DRF: last_update = serializers.SerializerMethodField() class Meta: model = hashtag fields = [ 'id', 'tag', 'date_display', 'last_update', 'timestamp', 'updated' ] def get_last_update(self,obj): return obj.updated.strftime('%b %d %I:%M %p') -
Return a queryset of all jobs that a logged in user applied for
I am building a job portal where users can apply for any job listed on the system. Assuming a user is logged in, and has applied for different job positions, I want to be able to return all the jobs he has applied for and pass it to my template. I have two models: Job and Applicants Models.py class Job(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) location = models.CharField(choices=country_state, max_length=20) description = RichTextUploadingField() requirement = RichTextUploadingField() years_of_experience = models.IntegerField(blank=True, null=True) type = models.CharField(choices=JOB_TYPE, max_length=10) last_date = models.DateTimeField() created_at = models.DateTimeField(default=timezone.now) date = models.DateTimeField(default=timezone.now) filled = models.BooleanField(default=False) def __str__(self): return self.title class Applicants(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) job = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='applicants') experience = models.IntegerField(blank=True, null=True) cv = models.FileField(upload_to=user_directory_path) degree = models.CharField(choices=DEGREE_TYPE, blank=True, max_length=10) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.get_full_name()} Applied' In my views.py I tried getting the logged in user with request.user and filter the Applicants model with the request.user. Then I filtered jobs in the applicant job list. Views.py class AppliedJobs(ListView): model = Applicants template_name = 'my_job_list.html' context_object_name = 'jobs' ordering = ['-date'] @method_decorator(login_required(login_url=reverse_lazy('login'))) def dispatch(self, request, *args, **kwargs): return super().dispatch(self.request, *args, **kwargs) def get_queryset(self): user = self.request.user my_job_list = Applicants.objects.filter(user=user).values_list('job', flat=True) return Applicants.objects.filter(job__in=my_job_list) I don't know … -
MAYAN-EDMS REST API: Documents are not getting checked in
Overview I'm try to maintain document versioning in MAYAN EDMS using REST API. If one user open and updating document then document will be checked out and on completion of changes user will check in document with new version which will be available for other users. Problem Documents are not getting checked in using REST API. It responds with status code 500 Error: Internal Server Error, without any exception etc. Swagger API Call Error Message -
Use seperate url for separate apps django
How can i use different domains for different apps. If user enters foo.com then it should open landing page of foo app and if he enters bar.com then it should open landing page of bar app. Please share the example -
how to group all records with multiple matching fields
this is my model and i'm using postgresql: class TripRequest(models.Model): ... passenger = models.ForeignKey('user.Passenger', on_delete=models.DO_NOTHING) beginning_point = models.PointField() beginning_locality = models.CharField(max_length=50, null=True) destination_point = models.PointField() destination_locality = models.CharField(max_length=50, null=True) ... how can i group all records that have matching beginning_locality and matching destination_locality? -
How to play a sound saved in a known directory with Django, via python script (not template)?
I am developing an app in Django. I have a mp3 file saved in directory my_project/static/sounds/1607.mp3 I have a script.py file located in my_project/my_app/my_folder How can I tell my django to play it at the end of a script.py? -
(index):135 POST http://127.0.0.1:8000/hom 403 error
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <script> function stopDefault(event) { event.preventDefault(); event.stopPropagation(); } function dragOver(label, text) { /* ADD ALMOST ANY STYLING YOU LIKE */ label.style.animationName = "dropbox"; label.innerText = text; } function dragLeave(label) { /* THIS SHOULD REMOVE ALL STYLING BY dragOver() */ var len = label.style.length; for(var i = 0; i < len; i++) { label.style[label.style[i]] = ""; } label.innerText = "Click to choose images or drag-n-drop them here"; } function addFilesAndSubmit(event) { var files = event.target.files || event.dataTransfer.files; document.getElementById("filesfld").files = files; submitFilesForm(document.getElementById("filesfrm")); } function submitFilesForm(form) { var label = document.getElementById("fileslbl"); dragOver(label, "Uploading images..."); // set the drop zone text and styling var fd = new FormData(); for(var i = 0; i < form.filesfld.files.length; i++) { var field = form.filesfld; fd.append(field.name, field.files[i], field.files[i].name); } var progress = document.getElementById("progress"); var x = new XMLHttpRequest(); if(x.upload) { x.upload.addEventListener("progress", function(event){ var percentage = parseInt(event.loaded / event.total * 100); progress.innerText = progress.style.width = percentage + "%"; }); } x.onreadystatechange = function () { if(x.readyState == 4) { progress.innerText = progress.style.width = ""; form.filesfld.value = ""; dragLeave(label); // this will reset the text and styling of the drop zone if(x.status == 200) { var images = JSON.parse(x.responseText); for(var i = 0; i < images.length; i++) … -
Use {% empty %} but in a form
I have a form : routine_form.html <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Créer une récurrence </legend> {{ form.media }} {{ form|crispy }} <div class="alert alert-warning" role="alert"> <strong>Astuce : </strong> Utilisez la touche <strong>CTRL</strong> sur Mac ou PC pour séléctionner plusieurs tâches. </div> </fieldset> <div class="form-group"> <button class="btn btn-success" type="submit">Ajouter</button> </div> </form> This form used the model RoutineList class Routinelist(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name="Nom de l'utilisateur") text = models.CharField(max_length=150, verbose_name="Nom de la Todo") Basicaly, RoutineList is used to create some tasks and then the form Routine used one or all of them to create a category like "Daily routine > wash my car > workout" etc. I want to show a message for when there is no task added by the user, something like "Please add a task first" I use the balise {% empty %} usually but it does not work here. -
when form is submit then a error is occur
when i click on remmber and submit the form then a error is occured MultiValueDictKeyError at /seller/ 'out' Request Method: POST Request URL: http://127.0.0.1:8000/seller/ Django Version: 2.2.7 Exception Type: MultiValueDictKeyError Exception Value: 'out' Exception Location: /home/krishan/.local/lib/python3.6/site-packages/django/utils/datastructures.py in getitem, line 80 Python Executable: /usr/bin/python3 Python Version: 3.6.8 Python Path: ['/home/krishan/Desktop/property', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/krishan/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Tue, 26 Nov 2019 10:27:23 +0000 views.py def register_seller(request): rm = request.POST.get('remember','off') if rm == 'on': if request.method == 'POST': userName = request.POST['userName'] state = request.POST['state'] city = request.POST['city'] full_address = request.POST['fulladdress'] out = request.FILES['out'] bedroom_no = request.POST['bedroom_no'] kithen_img = request.FILES['kitchen'] swimming_img = request.FILES['swimming'] phone = request.POST['phone'] email = request.POST['email'] price = request.POST['price'] floor = request.POST['floor'] squre = request.POST['squre'] garden_img = request.FILES['garden'] each = seller_detail(state=state,city=city,full_address=full_address,pro_img=out,username=userName,bedroom_no=bedroom_no,kitchen_img=kithen_img,swimming_img=swimming_img,phone=phone,email=email,price=price,floor=floor,squre=squre,gerden_img=garden_img) each.save() return redirect('home') else: return render(request,'all/seller_input.html',{'remember':'Please checkout the button'}) else: return render(request,'all/seller_input.html') -
Gunicorn failed with 203/EXEC
I'm trying to deploy my django project on CentOS 8 follow by this manual https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-centos-7 My project folder is /home/xmahop/support_cabinet/support_cabinet/manage.py virtualenv folder is /home/xmahop/support_cabinet/venv/ etc/systemd/system/gunicorn.service file is [Unit] Description=gunicorn daemon After=network.target [Service] User=xmahop Group=nginx WorkingDirectory=/home/xmahop/support_cabinet/support_cabinet ExecStart=/home/xmahop/support_cabinet/venv/bin/gunicorn --workers 3 --bind unix:/home/xmahop/support_cabinet/support_cabinet/support_cabinet/support_cabinet.sock support_cabinet.wsgi:application [Install] WantedBy=multi-user.target nginx conf: server { listen 80; server_name 192.168.136.131; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/xmahop/support_cabinet; location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/xmahop/support_cabinet/support_cabinet.sock; } } gunicorn status: Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: disabled) Active: failed (Result: exit-code) since Tue 2019-11-26 12:36:20 MSK; 33s ago Process: 9188 ExecStart=/home/xmahop/support_cabinet/venv/bin/gunicorn --workers 3 --bind unix:/home/xmahop/support_cabinet/support_cabinet/support_cabinet/support_cabinet.sock support_cabinet.wsgi:application (code=exited, status=> Main PID: 9188 (code=exited, status=203/EXEC) Nov 26 12:36:20 localhost.localdomain systemd[1]: Started gunicorn daemon. Nov 26 12:36:20 localhost.localdomain systemd[1]: gunicorn.service: Main process exited, code=exited, status=203/EXEC Nov 26 12:36:20 localhost.localdomain systemd[1]: gunicorn.service: Failed with result 'exit-code'. Nginx logs are empty. I'm tried chown xmahop:nginx to project folder and gunicorn conf file -
Sometime, object is not iterable
I try to solve this problem but I can't. It has a problem about iteration. views.py if borrow: borrow_item = Borrow_Item.objects.filter(borrow_id = borrow) for it in items: it_id = int(it) item_id = Item.objects.get(id=it_id) count = 0 for brit in borrow_item: if item_id.id == brit.item_id.id: count = count+1 break if count == 0: borrow_item = Borrow_Item(id=None, borrow_id=borrow, item_id=item_id) borrow_item.save() Sometime, it show " 'Borrow_Item' object is not iterable ". These are case that it's normal. Choose one new item. Choose more than one, by all items that select has been selected previously.(item is in cart) Choose two item, by choose one item has been selected and that item id less than another item id (new item). In the case that it causes an error. Choose more than one, by there are at least one item that has id less than existing items id Sorry, If I can't communicate to you to understand -
Integrating Dagster with Django
Hi I am trying to integrate Dagster into ongoing Django project. I am kind of struggling with providing Django context (models, apps, ...) to Dagster. As of now I am just checking wether dagit is present in sys.argv[0] in init.py of apps that are using Dagster. <!-- language: python --> ## project/app/__init__.py import sys import django if 'dagit-cli' in sys.argv[0]: print('dagit') django.setup() Can anyone help me with setup? -
I can not use django template-tag linebreak and justify
I try to justify some text that i get from my database but I also need to use the template-tag linebreak. html: <p class="justify">{{ article.contenu|linebreaks }}</p> css: .justify { text-align: justify!important; } My text won't justify itself unless I remove linebreak tag. Got any idea how to use justify and linebreak tag together ? Cordially -
Print Report in React (Client Side)
I have been stuck here for almost one month. I don't know how to achieve this one. After doing the rest task, I have to come back to this issue. Explanation Now I am doing a web app with reacts as front-end and Django as back-end that is a version upgrade from the desktop application. In the desktop application, I have done the report with crystal report and my client very likes this design. So Now client requests me to do the same design in the web app. Nightmare is coming now. How to print report in React or Django? My report has summary lines,group-by lines and other functions that support by crystal report, As u know, Event through these things are not the big deal in crystal report, In Web app, I have no idea for this. Should I print pdf with line and box and all things design by myself? I think this would be taken very long time because I have a lot of different design reports. I tried PDFMake but it does not support IE and JSPDF is I have no idea how to do for summary line and group-by line. Is there any way to … -
ModuleNotFoundError at /admin No module named 'winsound'
I am developing an app in Django. My app plays a sound using winsound module. import sys import winsound duration = 150 # milliseconds freq = 440 # Hz winsound.Beep(freq, duration) winsound.Beep(freq, duration) winsound.Beep(freq, duration) It worked fine as soon as I was developing in local, but when I pushed the app to heroku and then tryed to access the admin section, the web returned the error ModuleNotFoundError at /admin No module named 'winsound' So I tryed to pip install windsound , but apparently there is no moduled named so available for download. Thinking that the module was maybe already installed but with another name, I also tried pip freeze>requirements.txt and added 'winsound' in INSTALLED_APPS, but nothing worked. On the web I can find little information on winsound module and it appears it is not available to pip install with python... Does anybody knows how to solve it? -
My Django Admin fields does not show non asccii data correctly
I have a Django 1.11 Project with Mysql 5.7. When I write non-ASCII characters in the Django admin fields e.g. (چترال کا منظر), they display as ????????????. It does seem my database is not storing the data as I want it to; here is the my database charset. What am I missing here? -
Django NoReverseMatch at /provider/ 'provider ' is not a registered namespace
i'm learning Django and this my first project i have the above error for days trying to solve it . if i put blank html it will work but the below template makes error the HTML file is below {% extends 'base.html' %} {% block body %} <!-- Products --> <div class="total-ads main-grid-border"> <div class="container"> <div class="select-box"> <div class="browse-category ads-list"> <label>Browse Categories</label> <select class="selectpicker show-tick" data-live-search="true"> <option data-tokens="Mobiles">All</option> <option data-tokens="Mobiles">Mobiles</option> <option data-tokens="Electronics & Appliances">Electronics & Appliances</option> <option data-tokens="Cars">Cars</option> <option data-tokens="Bikes">Bikes</option> <option data-tokens="Furniture">Furniture</option> <option data-tokens="Pets">Pets</option> <option data-tokens="Books, Sports & Hobbies">Books, Sports & Hobbies</option> <option data-tokens="Fashion">Fashion</option> <option data-tokens="Kids">Kids</option> <option data-tokens="Services">Services</option> <option data-tokens="Jobs">Jobs</option> <option data-tokens="Real Estate">Real Estate</option> </select> </div> <div class="search-product ads-list"> <label>Search for a specific product</label> <div class="search"> <div id="custom-search-input"> <div class="input-group"> <input type="text" class="form-control input-lg" placeholder="Buscar" /> <span class="input-group-btn"> <button class="btn btn-info btn-lg" type="button"> <i class="glyphicon glyphicon-search"></i> </button> </span> </div> </div> </div> </div> <div class="clearfix"></div> </div> <div class="all-categories"> <h3> Select your category and find the perfect ad</h3> <ul class="all-cat-list"> </ul> </div> <ol class="breadcrumb" style="margin-bottom: 5px;"> <li><a href="/">Home</a></li> <li class="active"><a active href="{% url 'provider:provider_list' %}> All Categories </a> </li> {% if category %} <li class="active">{{category}} </li> {% endif%} </ol> <div class="ads-grid"> <div class="side-bar col-md-3"> <div class="search-hotel"> <h3 class="sear-head">Search</h3> <form method="GET" action="{% url … -
How to customize django group model
I want to change django default User and Group model relation from ManyToMany to OneToOne.But I don't know the right way to do this.I tried like this but the user field clashes roles.Role.user: (models.E006) The field 'user' clashes with the field 'user' from model 'auth.group' . models.py class Role(Group): user = models.OneToOneField(User,on_delete=models.CASCADE) -
I'am building online shop with python django
I'm working with Django to build online store and i built a cart system and i make a mistake i delete all product from data but when i deleted i found old product still on cart page and cart didn't work and give me this error enter image description here this is the cart class from decimal import Decimal from django.conf import settings from shop.models import Product from coupons.models import Coupon class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) # store current applied coupon self.coupon_id = self.session.get('coupon_id') if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart @property def coupon(self): if self.coupon_id: return Coupon.objects.get(id=self.coupon_id) return None def get_discount(self): if self.coupon: return (self.coupon.discount / Decimal('100')) \ * self.get_total_price() return Decimal('0') def get_total_price_after_discount(self): return self.get_total_price() - self.get_discount() def add(self, product, quantity=1, update_quantity=False): """ Add a product to the cart or update its quantity. """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0,'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): # mark the session as "modified" to make sure it gets saved self.session.modified = True def … -
Not able to authenticate Askbot with LDP authentication provider
Not able to authenticate Askbot django application on Ubantu 18.04- Able to ping the LDAP server, but still it says - "Can't contact LDAP server" Error logs shows:- Traceback (most recent call last): File "/srv/askbot/venv/local/lib/python2.7/site-packages/askbot/deps/django_authopenid/ldap_auth.py", line 127, in ldap_authenticate_default get_attrs File "/srv/askbot/venv/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 854, in search_s return self.search_ext_s(base,scope,filterstr,attrlist,attrsonly,None,None,timeout=self.timeout) File "/srv/askbot/venv/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 847, in search_ext_s msgid = self.search_ext(base,scope,filterstr,attrlist,attrsonly,serverctrls,clientctrls,timeout,sizelimit) File "/srv/askbot/venv/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 843, in search_ext timeout,sizelimit, File "/srv/askbot/venv/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 331, in _ldap_call reraise(exc_type, exc_value, exc_traceback) File "/srv/askbot/venv/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 315, in _ldap_call result = func(*args,**kwargs) SERVER_DOWN: {u'info': 'Transport endpoint is not connected', 'errno': 107, 'desc': u"Can't contact LDAP server"} -
How to pass value from HTML tag (other than <input> tag ) to view using Form?
How to pass value from HTML tag (other than tag ) to view using Form ? In Django I need to submit a form and pass the value holded in tag to view <div> <h3 class="media-title" id="user_name" name="user_name"> {{ username}} </h3> <button class="btn btn-small"> <a href="{% url 'add_to_group' %}"><i class="icon-plus">Add</i> </a> </button> </div> How do i fetch the value {{ username }} in view add_to_group ?