Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is here any in operator in Django ORM?
In one of my projects I have a database table named Doctor. I can run query like: expected_doctors = Doctor.objects.filter(id=4) or expected_doctors = Doctor.objects.get(id=4). But how can I find doctors whose id is in [1,2,3,4,5]; Like : expected_ids=[1,2,3,4,5] expected_doctors = Doctor.objects.filter(id in expected_ids) -
Format an exported date to excel with Django
With django-excel and using make_response(), I am exporting a column date which is a DateField like this : 2017-10-05T14:27:25.436299+00:00 I want to format this field to be more readable, like this: 10/05/2017 Is it possible to format my date in my exporting view? Here is my view : import django_excel as excel def export_client_download(request, atype): if request.user.groups.filter(name="Admin").exists(): if atype == "clients": query_sets = Profile.objects.filter(user__groups__name='Clients') columns_names = [ 'user__id', 'user__last_name', 'user__first_name', 'user__email', 'user__date_joined' ] sheet = excel.pe.get_sheet(query_sets=query_sets, column_names=columns_names) sheet.row[0] = [ 'ID', 'Last name', 'First Name', 'Email', 'Date' ] return excel.make_response(sheet, 'xls', file_name="clients") -
E1101:Instance of 'Generator' has no 'fake_url' , date, company member
populate_first_app.py import os os.environ.setdefault('DJANGO_SETTING_MODULE','first_project.settings') import django ##################### Fake pop script #################################### import random from first_app.models import AccessRecord, Webpage, Topic from faker import Faker fakegen = Faker() topics = ['search','social','Marketplace','news','Games'] def add_topic(): t = Topic.objects.get_or_create(top_name = random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): #get the topic for the entry top = add_topic() #create the fake data for that entry fake_url = fakegen.fake_url() #error fake_date = fakegen.date() #error fake_name = fakegen.company() #error #############################create a new page entry############################ webpg = Webpage.objects.get_or_create(top_name = random.choice(topics))[0] webpg.save() ##################3#create a faker access record for the webpage ############################ acc_rec = AccessRecord.objects.get_or_create(name= webpg, date= fake_date)[0] if __name__ == '__main__': print("population script") populate(20) print('populating complete! ') #####Create your models here.##########################3 #models.py from django.db import models class Topic(models.Model): top_name = models.CharField(max_length = 200, unique= True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey(Topic,on_delete=models.PROTECT) name = models.CharField(max_length = 200, unique= True) url = models.URLField(unique = True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage,on_delete= models.PROTECT) date = models.DateField() def __str__(self): return str(self.date) These are two files and I am getting an error in faker which has been downloaded properly error screenshot first 3 are errors and next are warmings due to pylint Screenshot -
Open pdf file in Django application
I would like to open PDF file inside my Django application, something like file:///... I know that a lot of posts state that this should not be done because security reason, and that google block this calls with error. link. But, I know that: I saw this behaviour so, I know it can be done somehow I don't have security risk, because application is internal, not connected to the internet (available over lan) Protocol file:/// wouldn't exist if there wouldn't be a way to use it. I also read somewhere that you need to put file in 'public' if you would like to access it via this method. Do anyone know how to do this? -
cookiecutter error in django
I installed a cookie cutter using pip Then I ran this $ cookiecutter https://github.com/pydanny/cookiecutter-django But this hasn't been working This is traceback Traceback (most recent call last): File "/home/choco/.local/bin/cookiecutter", line 7, in <module> from cookiecutter.__main__ import main ModuleNotFoundError: No module named 'cookiecutter' -
Heroku Django No Such App on Production Instance Only
The Dev instance of my Heroku Django application (free dyno) has suddenly starting coming up with "No Such App" when I click "Open App" from the dashboard, or manually visit the url eg https://www.dusk-garden-123.herokuapp.com/. It was working in the past, and I'm not sure what exactly caused it to stop working. Here is the output of "heroku domains --remote development": === safe-garden-36783 Heroku Domain safe-garden-36783.herokuapp.com My production instance is currently working and available at a custom https domain (on a hobby dyno). Any help would be appreciated -
Empty bytes received after using image PIL to compress image
I am trying to use PIL to compress my image uploaded by the django form. I will first get the image file using request.FILES['filePath'] then I open using PIL to read the image file and compress it and save it as InMemoryUploadedFile. I tried following the example here: link. However, when I tried to read the image file using imageDataBytes = file.read(), imageDataBytes return b' ' (empty bytes). Why is it so? When I read imageData, I see the bytes data but I'm unable to do it after opening in PIL and compressing it. Any assistance will be appreciated. Code: from PIL import Image as pil import io from django.core.files.uploadedfile import InMemoryUploadedFile imageName = request.FILES['filePath'].name imageData = request.FILES['filePath'] # jpeg/png content = imageData.content_type.split('/')[-1].upper() if(imageData): # opening file as PIL instance img = pil.open(imageData) img.thumbnail((160,300),pil.ANTIALIAS) thumb_io = io.BytesIO() # saving it to memory img.save(thumb_io,content,optimize=True,quality=85) file = InMemoryUploadedFile(thumb_io,'photo',imageName,imageData.content_type, None, None) #imageDataBytes: b'' imageDataBytes = file.read() -
django form should return data based on string comparison
Here is django form, In [61]: from django import forms In [62]: class myform(forms.Form): ...: f = forms.BooleanField(initial=False) ...: In [63]: x = myform({'f': '0'}) In [64]: x.is_valid() Out[64]: True In [65]: x.cleaned_data Out[65]: {'f': True} I am passing f as '0', cleaned_data is returning f as True. Expected behaviour : form should return False for '0' and True for '1', How do I achieve this ? -
Would an django ORM update command return before the update actually happens in Postgres?
I have a couple of lines of code that have an QuerySet.update call followed by an Instance.save call. Both on the same model, where the save call overwrites the initial update (e.g. Update a column in all records to X, then save the same column in my specific instance to Y). When performing the update command, could/would Postgres return a positive result before the update is completed? Somehow my the end result sometimes is behaving as if the update call happens after the save. By sometimes, I mean on our production servers where the DB is on a different physical machine to the application code. I can not reproduce this behavior locally on a Docker setup on my laptop (one container for Django, one for Postgres). -
"GET /static/article/bootstrap.min.css.map HTTP/1.1" 404 1700
I encounter error: "GET /static/article/bootstrap.min.css.map HTTP/1.1" 404 1700 when attempted to post a request using ajax: the jQuery was imported as: <script src="/static/js/jquery-3.3.1.js"></script> I solved the problem luckily by amending it to {% load staticfiles %} <script src="{% static 'js/jquery-3.3.1.js'%}"></script> However,I have little idea how this fixed the bug. -
Not working thread in python commands(management/commands)
app/management/commands/command_scheduler.py class Command(BaseCommand): def handle(self, *args, **kwargs): insert() import threading _thread = threading.Thread(target=insert) _thread.setDaemon(True) _thread.start() It is simple test code (I am using Apscheduler, BackgroundScheduler inserts in db but it is not executed.) Please reply. -
Using pagination with a filtered results, doesn't work
I have a Class Based View with pagination: class ItemListView(ListView) paginate_by= 10 By default is working ok. In a normal site users, use search, and in some cases the search is also paginated. The search is done overwriting get_queryset. def get_queryset(self, *args, **kwargs): if self.request.GET.get('q'): qs = qs.objects.filter(keyword=self.request.GET.get('q')) In template I have: <li> <a href="?page={{ page_obj.number}}">&raquo;</a> </li> My issues, is when I click on the search listing second page, it goes to the 'full list' pagination. So, the page_object is ignoring the 'initial queryset' and is doing its own default queryset. How can I fix it ? -
'My_Model' object is not iterable using customtag in django
I am new to Django and I am trying to make my data accessible to templates in different apps by creating custom tags in Django. my model.py from django.db import models class my_Model(models.Model): name = models.CharField(max_length=20) age = models.CharField(max_length=20) my custom tag file templatetag/custom_tag.py(why I did this is to make my data accessible to templates in different apps) from django import template from model_file.models import my_Model register = template.Library() @register.simple_tag def get_custom_tag_fn(): return my_Model.objects.all() my html file {% load custom_tag %} {% get_custom_tag_fn as ct %} {% for item in ct %} <p> {{ item }} </p> {% endfor %} I am getting the error 'My_Model' object is not iterable. Any thought about how to solve this. -
How to upload large audio file to a django server given a blob url?
I've got a javascript that records audio using MediaRecorder and pushes the binary data into an array chunk. Once the user finishes recording, the data is converted into a blob and loaded to an HTML's audio element for playback. My issue is now trying to load this data onto the Django server at the same time. Most sample upload script I've seen has users manually loading an audio file into a form's input element and manually hitting a submit button, but my data is already loaded into a blob file so I am not sure how to proceed. HTML <div id="buttons"> <form> <button id="record_btn" style="">Record</button> <input id="stop_btn" type="submit" value="Stop" disabled> <audio id="audio" controls> <source id="source" src="" type="audio/ogg"/> </audio> </form> </div> Javascript var record = document.querySelector('#record_btn'); var stop = document.querySelector('#stop_btn'); if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { console.log('getUserMedia supported.'); navigator.mediaDevices.getUserMedia ( // constraints - only audio needed for this app { audio: true }) // Success callback .then(function(stream) { var mediaRecorder = new MediaRecorder(stream); record.onclick = function() { mediaRecorder.start(); record.disabled = true; stop.disabled = false; console.log(mediaRecorder.state); console.log("recorder started"); record.style.background = "red"; record.style.color = "black"; } var chunks = []; mediaRecorder.ondataavailable = function(e) { chunks.push(e.data); } stop.onclick = function() { mediaRecorder.stop(); record.disabled = false; … -
Associate classes with django-filters
I have a question regarding django-filters. My problem is: I have two classes defined in my models.py that are: class Volcano(models.Model): vd_id = models.AutoField("ID, Volcano Identifier (Index)", primary_key=True) [...] class VolcanoInformation(models.Model): # Primary key vd_inf_id = models.AutoField("ID, volcano information identifier (index)", primary_key=True) # Other attributes vd_inf_numcal = models.IntegerField("Number of calderas") [...] # Foreign key(s) vd_id = models.ForeignKey(Volcano, null=True, related_name='vd_inf_vd_id', on_delete=models.CASCADE) The two of them are linked throught the vd_id attribute. I want to develop a search tool that allows the user to search a volcano by its number of calderas (vd_inf_numcal). I am using django-filters and for now here's my filters.py: from .models import * import django_filters class VolcanoFilter(django_filters.FilterSet): vd_name = django_filters.ModelChoiceFilter( queryset=Volcano.objects.values_list('vd_name', flat=True), widget=forms.Select, label='Volcano name', to_field_name='vd_name', ) vd_inf_numcal = django_filters.ModelChoiceFilter( queryset=VolcanoInformation.objects.values_list('vd_inf_numcal', flat=True), widget=forms.Select, label='Number of calderas', ) class Meta: model = Volcano fields = ['vd_name', 'vd_inf_numcal'] My views.py is: def search(request): feature_list = Volcano.objects.all() feature_filter = VolcanoFilter(request.GET, queryset = feature_list) return render(request, 'app/search_list.html', {'filter' : feature_filter, 'feature_type': feature_type}) In my application, a dropdown list of the possible number of calderas appears but the search returns no result which is normal because there is no relation between VolcanoInformation.vd_inf_numcal, VolcanoInformation.vd_id and Volcano.vd_id. It even says "Select a valid choice. That … -
django model_to_dict including foreignkeys pointing to model
I have a model: class Main(models.Model): name = models.CharField(max_length=99) Which has multiple inlines: class First(models.Model): Main = models.ForeignKey(Main, on_delete=models.CASCADE) option = models.ForeignKey(Option, on_delete=models.CASCADE) class Second(models.Model): Main = models.ForeignKey(Main, on_delete=models.CASCADE) option = models.ForeignKey(Option, on_delete=models.CASCADE) I'm trying to send a specific object "main" with all of it's inlines (First and Second). But whenever I do: 'main': model_to_dict(main) It will only pass the "name" value from within the Main class, and it will ignore all the inline values. I've looked at a few other questions similar to this and tried their solutions but unfortunately changing it to: 'main': main.__dict__ doesn't work. I tried my own model_to_dict here: def model_to_dict(instance, include=None, exclude=None): fields = instance._meta.concrete_fields if include is not None: return {f.attname: getattr(instance, f.attname) for f in fields if f.name in include} if exclude is not None: return {f.attname: getattr(instance, f.attname) for f in fields if f.name not in exclude} return {f.attname: getattr(instance, f.attname) for f in fields} Also didn't pass the inlines. Is there any easy way to pass these through a JsonResponse? Thanks -
GDAL library missing error
I am trying to run a Django application (new to Django development). When I try to run it, it gives me an error saying 'OSError: [WinError 126] The specified module could not be found.' I tried resolving it by installing GDAL python library, pointing gdal.h c library and gdal dll file. still the error persists. Below is the description of the error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000021343D46378> Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\ProgramData\Anaconda3\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\ProgramData\Anaconda3\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\ProgramData\Anaconda3\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\ProgramData\Anaconda3\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, … -
This error is happening in django
NameError at /shop/ global name 'get_object_or_404' is not defined Request Method: GET Request URL: http://localhost:8000/shop/ Django Version: 1.11.13 Exception Type: NameError Exception Value: global name 'get_object_or_404' is not defined Exception Location: /var/www/senv/myshop/shop/views.py in product_list, line 18 Python Executable: /var/www/senv/bin/python Python Version: 2.7.15 Python Path: ['/var/www/senv/myshop', '/var/www/senv/lib/python2.7', '/var/www/senv/lib/python2.7/plat-x86_64-linux-gnu', '/var/www/senv/lib/python2.7/lib-tk', '/var/www/senv/lib/python2.7/lib-old', '/var/www/senv/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/var/www/senv/local/lib/python2.7/site-packages', '/var/www/senv/lib/python2.7/site-packages'] Server time: Mon, 2 Jul 2018 06:16:31 +0000 -
Limit Choices of Foreign Keys in DRF
I have model Commodity: class Commodity(models.Model): shop = models.ForeignKey(Shop, related_name='commodity', on_delete=models.CASCADE) brand = models.ForeignKey(Brand, blank=True, null=True, on_delete=models.CASCADE) price_old = models.DecimalField(max_digits=10, decimal_places=2) price_new = models.DecimalField(max_digits=10, decimal_places=2) I tried to use limit_choices_to and it didn't work. I have a Serializer: class CommoditySerializer(serializers.ModelSerializer): image = CommodityImageSerializer(many=False) def get_queryset(self): user = self.context['request'].user queryset = Commodity.objects.filter(shop__company__user=user) return queryset class Meta: model = Commodity fields = ('id', 'shop', 'brand', 'price_old', 'price_new') This get_queryset also dont help me. Finally I have a regular CreateAPIView, and this method also dont help me. How can I limit usage of foreign keys? I need to let create commodities to my user only within user's Shops. THanks! -
How to paginate more than two object lists in one page - Django get_context_data()
Suppose I have two or more than two object lists objects_a and objects_b in Views.py with get_context_data() of Django, and I would like to paginated for objects_a and objects_b, I pasted my objects_list.html as below too, which can only paginated one of objects, objects_a or objects_b, how to paginated both of objects? I have more than two object lists, four or five lists, how to paginate more than two object lists in one page? Thank you so much for any advice. class ObjectListView(PaginationMixin, ListView): model = Object ordering = ('name', 'department') context_object_name = 'objects' template_name = '' paginate_by = 20 def get_queryset(self, **kwargs): queryset = Permit.objects.all() return queryset def get_context_data(self, **kwargs): ................. obejcts_a = ........ obejcts_b = ........ ................. extra_context = { "objects_a": objects_a, "objects_b": objects_b, } kwargs.update(extra_context) return super().get_context_data(**kwargs) Here is my objects_list.html of objects_a and objects_b, {% extends 'base.html' %} {% block content %} <nav aria-label="breadcrumb"> </nav> <h3 class="mb-3">List of object A</h3> <div class="card"> <table class="table mb-0"> <thead> <tr> <th>Name</th> <th>Department</th> <th></th> </tr> </thead> <tbody> {% for object in objects_a %} <tr> <td class="align-middle">{{ object.name }}</td> <td class="align-middle">{{ object.department.name }}</td> </tr> {% empty %} {% endfor %} </tbody> </table> </div> <br> <h3 class="mb-3">List of object B</h3> <div class="card"> … -
django error NameError: name 'DEBUG' is not defined
i am running my django framework and this error show up , i checked online but did not find any solution here is the error it show Traceback (most recent call last): File "manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "C:\Program Files (x86)\Emacs\.virtualenvs\back-97G-SXVS\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Program Files (x86)\Emacs\.virtualenvs\back-97G-SXVS\lib\site-packages\django\core\management\__init__.py", line 317, in execute settings.INSTALLED_APPS File "C:\Program Files (x86)\Emacs\.virtualenvs\back-97G-SXVS\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Program Files (x86)\Emacs\.virtualenvs\back-97G-SXVS\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Program Files (x86)\Emacs\.virtualenvs\back-97G-SXVS\lib\site-packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Program Files (x86)\Emacs\.virtualenvs\back-97G-SXVS\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\_monster\Desktop\skill\djember_cookiecutter\djember_test\back\settings.py", line 161, in <module> if DEBUG: NameError: name 'DEBUG' is not defined so anyone have any idea ? -
Django-notification invalid literal for int() with base 10
I'm using django-notification to create notifications. based on it's documention I putted: url(r'^inbox/notifications/', include(notifications.urls, namespace='notifications')), in my urls.py. I generate a notification for test by using this in my views.py: guy = User.objects.get(username = 'SirSaleh') notify.send(sender=User, recipient=guy, verb='you visted the site!') and I can easily get the number of unread notification in this url: http://127.0.0.1:8000/inbox/notifications/api/unread_count/ it return {"unread_count": 1} as I want. but with /api/unread_list/ I can not to get the list of notifications and I get this error: ValueError at /inbox/notifications/ invalid literal for int() with base 10: '<property object at 0x7fe1b56b6e08>' As I beginner in using django-notifications any help will be appreciated. -
How to exit views function if queryset not found not found in database
I have two apps in my django project "card" and "blog" my project urls.py is : urlpatterns = [ path('admin/', admin.site.urls), path(r'', include(card.urls)), path('', include('blog.urls')),] url.py for "card" app is: urlpatterns = [ re_path(r'^(?P<card_url_var>[-\w.]+)/$', views.carddet, name='carddetail'),] views.py for "card" app is: def carddet(request, card_url_var): try: url_carddetails = carddata.objects.get(page_end_url=card_url_var) except carddata.DoesNotExist: raise Http404("Card you are looking for, does not exists") Now urls.py for "blog" apps is: urlpatterns = [ re_path(r'^(?P<art_url_var>[-\w.]+)/$', views.articledet, name='articledetail'),] viws.py for blog apps is: def articledet(request, art_url_var): try: url_articledetails = articledata.objects.get(art_end_url=art_url_var) except articledata.DoesNotExist: raise Http404("Article you are looking for, does not exists") When I request urls that are in "page_end_url" column of "carddata" model the code works fine. But when I request urls that are in "art_end_url" column of "articledata" model it returns Http404 "Card you are looking for, does not exists". For Example: If I request example.com/new-year-card-2018 The Code works fine because "new-year-card-2018" exists in "page_end_url" column. But If i request example.com/best-designs-of-2018 The url "/best-design-of-2018" whis is saved "art_end_url" attribute of "articledata" model. The code returns Http404 "Card you are looking for, does not exists" P.S: I have also tried: except: return redirect('articledetail') in views.py of card app it returns error with: Reverse for 'articledetails' with no … -
How to extend django admin history log and add custom fields?
I want to add custom fields in django admin history log. How do i extend the admin ModelAdmin.history_view(request, object_id, extra_context=None) -
User login info is deleted when I delete posts
User login info is deleted when I delete posts.I wrote in views.py def top(request): if request.method == 'POST': loginform = LoginForm(request, data=request.POST) if loginform.is_valid(): user = loginform.get_user() info = Info.objects.order_by('-created_at') return render(request, 'top.html', {'info':info,'user': user}) loginform = LoginForm() info = Info.objects.order_by('-created_at') return render(request, 'top.html',{'info':info,'loginform':loginform,'user': request.user}) def delete(request): delete_ids = request.POST.getlist('delete_ids') if delete_ids: Info.objects.filter(id__in=delete_ids).delete() return redirect(reverse("app:top")) in top.html <div> {% if user and not user.is_anonymous %} <h2>{{ user.username }}</h2> {% else %} <form action="" method="POST"> <div> {{ loginform.non_field_errors }} {% for field in loginform %} {{ field }} {{ field.errors }} {% endfor %} </div> <button type="submit">LOGIN</button> {% csrf_token %} </form> {% endif %} <div> <form action="{% url 'app:delete' %}" method="POST"> {% csrf_token %} {% for i in info %} <input id="chkbox" type="checkbox" name="delete_ids" value="{{ i.pk }}" /> <div> <p>{{ i.name }}</p> </div> {% endfor %} <button type="submit">Delete</button> </form> Firstly I login to this app by putting LOGIN button,user.username is shown. And when I put Delete button to delete info,login info is deleted too(user.username is not shown).info is deleted but I really cannot understand why login info is deleted too.I cannot send user's info in redirect(reverse("app:top")),so shouldn't I use redirect?How should I fix this?