Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django invoice model formset
I am trying to create an invoice form. I am trying to use a formset because the products will be added more than once in the sales process. I am constantly failing in form creation. My Models: class Fatura(models.Model): musteri = models.ForeignKey(CariModel, on_delete=models.CASCADE, blank=False) fatura_tarihi = models.DateField(auto_now=True, blank=False) fatura_numarasi = models.CharField(max_length=36, default=fatura_numarasi) odeme_tarihi = models.DateField(auto_now=False, blank=True) def __str__(self): return "{} - {}".format(self.musteri, self.fatura_numarasi) class FaturaUrunler(models.Model): fatura = models.ForeignKey(Fatura, on_delete=models.CASCADE, blank=False) baslik = models.CharField(max_length=128, blank=False) urun = models.CharField(max_length=128, blank=False) miktar = models.DecimalField(max_digits=12, decimal_places=3, default=1) fiyat = models.DecimalField(max_digits=12, decimal_places=3) vergi = models.CharField(choices=KDV, default=18, max_length=5) My Views: def index(request): class GerekliFormlar(BaseFormSet): def __int__(self, *args, **kwargs): super(GerekliFormlar,self).__init__(*args, **kwargs) self.queryset = Fatura.object.none() UrunlerFormset = formset_factory(UrunForm, max_num=0, formset=GerekliFormlar) if request.method == 'POST': fatura_form = FaturaForm(request.POST) urunler_formset = UrunlerFormset(request.POST, request.FILES) if fatura_form.is_valid() and urunler_formset.is_valid(): fatura = fatura_form.save() for form in urunler_formset.forms: urunler = form.save() urunler.fatura = fatura urunler.save() return HttpResponse("tesekkürler") else: fatura_form = FaturaForm() urunler_formset = UrunForm() c = { 'fatura_form': fatura_form, 'urunler_formset': urunler_formset } c.update(csrf(request)) return render_to_response('anasayfa_gecici.html', c) I would like to make customer selection and product addition within the form. Simple billing system -
Django - Make query to join three tables with prefetch_related
I am using Django 1.11. I have three tables. A(models.Model): name = models.CharField(max_length=128) B(models.Model): name = models.CharField(max_length=128) a = models.ForeignKey(A, related_name='b') D(models.Model): name = models.CharField(max_length=128) a = models.ForeignKey(A) Is it possible to get all D's with their corresponding rows from B using prefetch related? I want to refer fields in D model and compare with B model while making that prefetch query. May be something like this: D.objects.filter(name='abc').select_related( 'a' ).prefetch_related(Prefetch( 'a__b', queryset=B.objects.filter(name=F('d__name')) )) -
reCaptcha appearing at the top of my form even though I've put it at the bottom in my HTML
Using the django-recaptcha package to use reCaptcha in my django-allauth signup form (doesn't really matter, I was having the same problem without the package). So I simply place the reCaptcha ({{ form.captcha }}) after my form inputs (but before the submit input): <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{ form.as_p }} {{ form.captcha }} {{ form.captcha.errors }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button type="submit">{% trans "Sign Up" %} &raquo;</button> </form> form.as_p is the form inputs. However, this is how it renders on the page: <form class="signup" id="signup_form" method="post" action="/accounts/signup/"> <input type='hidden' name='csrfmiddlewaretoken' value='nnq5OVApZrOs00ryvyPpVZYVHPKveyZzIQrP7E9PjBdFOHo4kfhEqBzGWg0ug' /> <p><label for="id_captcha">Captcha:</label> <script src="https://www.google.com/recaptcha/api.js?hl=en"></script> <div class="g-recaptcha" data-sitekey="l0eIxAcTAAXXAJcZVRqyHxc1UMIEGNQ_23jiZKhI" data-theme="clean" data-id="id_captcha" data-required="True" ></div> <noscript> <div style="width: 302px; height: 352px;"> <div style="width: 302px; height: 352px; position: relative;"> <div style="width: 302px; height: 352px; position: absolute;"> <iframe src="https://www.google.com/recaptcha/api/fallback?k=l0eIxAcTAAXXAJcZVRqyHxc1UMIEGNQ_23jiZKhI" frameborder="0" scrolling="no" style="width: 302px; height:352px; border-style: none;"> </iframe> </div> <div style="width: 250px; height: 80px; position: absolute; border-style: none; bottom: 21px; left: 25px; margin: 0px; padding: 0px; right: 25px;"> <textarea id="g-recaptcha-response" name="g-recaptcha-response" class="recaptcha_challenge_field" style="width: 250px; height: 80px; border: 1px solid #c1c1c1; margin: 0px; padding: 0px; resize: none;" value=""> </textarea> <input type="hidden" name="recaptcha_response_field" value="manual_challenge" /> </div> </div> </div> </noscript></p> … -
Django admin custom field ordering
I'm trying to make custom filter order. Below is my Admin Code for it search_fields = ('user', 'title','id','content') readonly_fields = ('user','modified_date','created_date') list_display = ('title','user',,'comment_count','like_count','created_date') list_filter = ('view_count',) fieldsets = ( ('Infos',{ 'fields':(('user','top_notice','type',),('created_date','modified_date')) }), ('Title & Content',{ 'fields':(('title','content')) }) ) list_per_page = 10 def comment_count(self, obj): return ForumComment.objects.filter(article=obj).count() comment_count.short_description = 'Comments Count' def like_count(self,obj): return Forumlike.objects.filter(article=obj,islike=True).count() like_count.short_description = "Likes Count" Like above I have made a custom field to load comments and likes count. But the main needs for the field is ordering. But if I add comment_count.admin_order_field = 'comment_count' This code below it says Cannot resolve keyword 'comment_count' into field. Since this problem is trying to load other model Similiar problem soulution didn't work out. I do not want default sort as comment count or forum like. I would like admins choose it. Is there any solutions for it? Thanks. -
'latin-1' codec can't encode characters in position 67-70: ordinal not in range(256)
I have a url link that contains some Chinese characters( http://localhost:8000/media/imges/qiyun_admin_physicalserver_webmanage/operation_system/域名解析.png ) for request, if I copy the Chinese contained url from browser address bar, it become this: http://localhost:8000/media/imges/qiyun_admin_physicalserver_webmanage/operation_system/%E5%9F%9F%E5%90%8D%E7%BB%91%E5%AE%9A.png there gets the error: 'latin-1' codec can't encode characters in position 67-70: ordinal not in range(256) I found a related post in SO: UnicodeEncodeError: 'latin-1' codec can't encode character I have checked the database use the utf-8 encode, and the table is utf-8 too: But why I get the encode error? How to solve this issue? My backend is Django/Django-Rest-Framework. -
non-DB backend for Django Apps
I'm trying to integrate wsgi python app into a Django app as a controller - The App will provide the output and input (eg. as A dictionary) and send the data to view/controller. I do not need a DB backend because the commands will be run on the go through wsgi and the output won't be stored in a DB. What is the best approach to accomplish this goal? Is it Django suitable for it? Thanks in advance -
django invalid literal for int() with base 10: 'game_count'
I am making simple application by django that the counters go up one by one if user click button. When I ran following code, then it displays the error message "invalid literal for int() with base 10: 'game_count'" what is the cause of this problem? models.py class User(models.Model): game_count = models.IntegerField(default=0) views.py from django.shortcuts import render from .models import User from .forms import CountForm def user(request): form = CountForm(request.POST or None) game_count = User.objects.get(game_count='game_count') if request.method == 'POST' and form.is_valid(): game_count += 1 game_count.save() return render(request, 'app/user.html', {'count':game_count}) forms.py from django import forms from .models import User class CountForm(forms.ModelForm): class Meta: model = User fields = ("game_count",) user.html <p>{{ count }}</p> <form action="" method="POST"> <button type="submit">go</button> {% csrf_token %} </form> -
Django asyncio call in views doesn't work
I'm struggling on this problem for quite a moment now. I'm trying to export a view in pdf, using pyppeteer. Here are my functions : async def export_pdf(url): browser = await launch() page = await browser.newPage() await page.goto(url) pdf = await page.pdf( { 'printBackground': True } ) await browser.close() return pdf And call it like that in my view: response.content = asyncio.get_event_loop().run_until_complete( export_pdf(self.request.get_full_path()) ) But I got this error RuntimeError at /export-pdf/1/2018/1/1/ There is no current event loop in thread 'Thread-1'. After some research I thought someone solved my problem and I called it like that (didn't quite understand, but it's something about django and my function not called in the main thread): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) response.content = loop.run_until_complete( export_pdf( asyncio.wait( export_pdf(self.request.get_full_path()) ) ) ) loop.close() But now I have this error : TypeError at /export-pdf/1/2018/1/1/ expect a list of futures, not coroutine I'm quite new to async in python, and the thing is, when i copy and paste the exact same code in my ipython shell, everything works fine. Any explanation / light would be appreciated ! Thanks in advance. -
I keep getting this error 'Manager isn't accessible via Post instances' in django 1.10
Here are my codes in models.py class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager,self).get_queryset().filter(status='published') -
How do I perform aggregation on date and time in Django?
Let's say I have the following simplistic model, for demonstration purposes: class Something(models.Model): date = models.DateField() time = models.TimeField() timestamp = models.DateTimeField() price = models.DecimalField() manufacturer = models.CharField() If I want to get the total count of every manufacturer I can do something like below: Something.objects.all().values("manufacturer").annotate(frequency=Count(field)) My aim is to do something similar based on the date and time. For example the total count for every month. My first thought since there are already data based on the model above is to add a custom property, but you can not use it with values. Next, I thought to add the neccessary fields(day,month,year,...) to the model and add a custom save method to calculate them. Another way is to load the queryset into pandas and do the calculations there. Is there a more appropriate way to do something like this ? -
Django: POST request successful but nothing on backend
I am facing a small problem in my Django app and not able to figure out what is wrong with it. I have a POST request that is getting sent successfully from the front-end, the django console also hits the URL and gives a status code 200. But the problem is that the view is not getting triggered at all. /urls.py urlpatterns = [ url('addition/', views.addition_task, name='addition'), url('addition-task-status/', views.addition_task_status, name='addition_task_status'), url('', views.algorithm_index, name='algorithm_index'), url('outlier/', views.run_outlier_task, name='run_outlier'), url('outlier-task-status/', views.outlier_task_status, name='outlier_task_status'), ] /views.py @csrf_exempt def run_outlier_task(request): print("I'm here") if request.method == "POST": print("Request is post") metric = request.POST["metric_variable"] print(metric) path = ['MKT', 'CP_MANUFACTURER', 'CP_FRANCHISE', 'CP_BRAND', 'CP_SUBBRAND'] drivers = ['Cumulative_Distribution_Pts', 'pct_Stores_Selling', 'Baseline_RASP_per_EQ'] if request.session.get('file_path', None) == None: file_name = "anon_cntr_out_br.csv" else: file_name = request.session.get('file_path', None) outlier_task = outlier_algorithm.delay(path, metric, file_name, drivers) return HttpResponseRedirect(reverse("outlier_task_status") + "?job_id=" + outlier_task.id) else: return HttpResponse("GET Request") def outlier_task_status(request): if 'job_id' in request.GET: job_id = request.GET['job_id'] job = AsyncResult(job_id) data = job._get_task_meta() return HttpResponse(json.dumps(data['result'])) else: HttpResponse("No job ID given") /templates/algorithm.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Algorithms</title> </head> <body> <div> <form action="{% url 'run_outlier' %}" method="post"> {% csrf_token %} <input type="text" name="metric_variable"> <input type="submit" value="Run algo with default file and attributes" /> </form> </div> </body> </html> Please let … -
ImportError: cannot import name 'FieldPanel' (Wagtail)
When i try to make an abstractUser Model Class i get this error message after i put AUTH_USER_MODEL = 'blog.User' in my settings.py i followed the Wagtail custom user model example The Link to the site. Im using django 1.11.3 and wagtail 2.0, python 3.5.4 Sitename = mysite Appname = Blog Model = Models.py User class Stack Trace (wagtail-9p7xWA1-) 0-10:22-/mnt/c/dev/wagtail/mysite (master) $ ./manage.py runserver Unhandled exception in thread started by .wrapper at 0x7fc502ce8840> Traceback (most recent call last): File "/home/Username/.local/share/virtualenvs/wagtail-9p7xWA1-/lib/python3.5/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/Username/.local/share/virtualenvs/wagtail-9p7xWA1-/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/home/Username/.local/share/virtualenvs/wagtail-9p7xWA1-/lib/python3.5/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "/home/Username/.local/share/virtualenvs/wagtail-9p7xWA1-/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/Username/.local/share/virtualenvs/wagtail-9p7xWA1-/lib/python3.5/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/Username/.local/share/virtualenvs/wagtail-9p7xWA1-/lib/python3.5/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/Username/.local/share/virtualenvs/wagtail-9p7xWA1-/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/home/Username/.local/share/virtualenvs/wagtail-9p7xWA1-/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/home/Username/.local/share/virtualenvs/wagtail-9p7xWA1-/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in _find_and_load File "", line 958, in _find_and_load_unlocked File "", line 673, in _load_unlocked File "", line 665, in exec_module File "", line 222, in _call_with_frames_removed File "/mnt/c/dev/wagtail/mysite/home/models.py", line 5, in from wagtail.admin.edit_handlers import FieldPanel File "/home/Username/.local/share/virtualenvs/wagtail-9p7xWA1-/lib/python3.5/site-packages/wagtail/admin/edit_handlers.py", line 23, in from … -
gunicorn cannot server a simple django API which needs preloading large file into memeory
Recently I work on developping an API with Django. Since the computing process is very time-consuming, the API was designed to preload large file into memeory to speed up this process. Specificly, I wrote a data_loader.py, and import it in view.py of this django project. When I starting the project with django's own server (python3 mananage.py runserver), you can see everything is OK --- the data was loaded into memory as global variables used for the whole project. Most importantly, it is only loaded once, thus the subsequent computing process will be very rapid. django's own server It is heared that gunicorn outperforms django's own runserver, thus, I turned to use gunicorn to server this API (gunicorn -b 0.0.0.0:9000 myAPI:wsgi:applications). However, I noticed that the information of loading data didnot appear with gunicorn starting. gunicorn server Only when I send requests to gunicorn , the server begins to call data_loader.py to load data into memerory, and worst of all, it reload data_loader.py (that's the most time-consuming process) everytime I send a request. What I want is developping an API like the style of Django's own server -- it only load data once, the data is always in memeory and could … -
How to compress uploaded image in django python
have been going through many tutorials on python on how to compress images, Have used PILLOW but its not working. I will be grateful if I can get a full documentation on how to use PILLOW for image compression inside my django views.py -
vscode can not recognize Django ManyToManyField's clear and add method
I want to use vscode to write Django code, and i have installed pylint and pylint-django, the settings.json like this: vscode can recognize "models.objects", but can not recognize ManyToManyField method, the output as follow: Do you have any solution? -
How to get google drive credential in Django web backend?
I am a newbie to google drive. I am building file upload functionality with Django. So, to initialize google drive service, I just needed to get credential. Here is codebase. def get_credentials(): home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'drive-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials I don't have the credential in drive-python-quick.json file, so going to if case. credentials = tools.run_flow(flow, store) Seems tools.run_flow() is only for the command line, I can't use it in API. How can I get credential? -
How to use <username> in detailview for django 2.0
class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=40, blank=True) bio = models.TextField(max_length=500, null=True, blank=True) def get_absolute_url(self): return reverse('userprofile:to_profile', args=[str(self.user.username)]) So I have made this model to save it as whatever.com/userprofile:to_profile/thisisusername And on url, I have path('accounts/profile/<username>/', ProfileDetailView.as_view(), name="to_profile"), For the view, I have class ProfileDetailView(DetailView): model = Profile template_name = "account/profile.html" I do know that default DetailView takes pk and slug but whenever I try to pass the username with pk_url_kwarg = "username" I get an error invalid literal for int() with base 10 Is there anyway we can use username for generic detailview? or is pk the only way to go? -
Django DRY verbose names with foreign keys?
class ModelA(models.Model): class Meta: verbose_name = 'my awesome name' class ModelB(models.Model): some_field = models.ForeignKey(ModelA) Is there a way to make some_field's verbose_name to be my awesome name without being explicit about it? (ie. using the verbose name related class as a default field verbose name, instead of using the attribute name) I actually think this should be the default Django behaviour. -
Hide the form fields along with their labels
I am relatively new to Django. I am facing some issue in django where i need to hide some form fields along with their labels and help text with checkbox click. i have written a javascript to this which is working but only input fields getting hiding not the labels and help text. Please help. thanks. -
Filtering objects with each object's foreignkey property and object's many to many property
I have a basic chat model: class Thread(models.Model): created_at = models.DateTimeField(default=timezone.now) members = models.ManyToManyField(User, through='Membership', through_fields=('thread', 'user')) class Membership(models.Model): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) date_joined = models.DateTimeField(default=timezone.now) class Message(models.Model): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) sender = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() timestamp = models.DateTimeField(default=timezone.now) I am trying to filter an object by its foreignkey field's property, with the object's many to many fields data. Meaning, I would like to get only those threads whose message timestamp is greater than user's membership date joined for the thread. Example: Thread.objects.filter(members=user, message__timestamp__gte= < thread's user's membership date joined >).distinct() I can create a for loop and go through each of the threads and then return a new list, but is there any way that I could do it while filtering itself or maybe there is a better way? -
How to drop App table with Django and Postgres
I'm trying to drop a single table from my App's database in a Django project. When I enter the database shell using manage.py dbshell, I try to execute DROP TABLE mytable; and get ERROR: table "mytable" does not exist I think the cause of this stems from the database thinking I'm in my project directory instead of my app directory but I don't know how to change that. This is what the shell looks like after I type ./manage.py dbshell: myproject=# DROP TABLE mytable; ERROR: table "mytable" does not exist I think instead of myproject=# it should say something like myapp=# or myproject/myapp=# but I do not know how to accomplish this. -
Viewset's list() and Filtering conflict
When I set a ViewSet with both filtering and list() function -> filtering stops work: class ClientViewSet(ModelViewSet): serializer_class = ClientSerializer queryset = Client.objects.all() filter_class = ClientFilter def list(self, request): serializer = ClientSerializer(self.queryset, many=True) return JsonResponse(serializer.data, safe=False) Here is my filter class: class ClientFilter(FilterSet): type = CharFilter(name='type', lookup_expr='iexact') parent_id = NumberFilter(name='parent__id') title = CharFilter(name='title', lookup_expr='icontains') class Meta: model = Client fields = { 'type', 'parent_id', 'title' } Please note that without a list() method filtering works perfectly, I checked that thousand times. I'm 100 % sure that list() is exactly what causing the issue, I just don't know why and what exactly to do to solve this conflict. -
what response should I return when create excel in Django REST framework
backend: Django REST framework frontend: node.js VUE I use openpyxl create a workbook, and return a Response like this: from openpyxl import Workbook wb = Workbook() response = HttpResponse(save_virtual_workbook(wb), content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="foo.xlsx"' return response but frontend coder said he accept gibberish, you should return a bytearray like 0101010101,he can analysis and download Now I return a response like this, he use node.js not vue download through a complex process I am confused, what should I do? -
How django add objects attribute to model classes?
As in the django documentation By default, Django adds a Manager with the name objects to every Django model class How does django add a attribute to model classes? Whether it is inherited from the models.Model or django add objects=models.Manager() dynamically to each models? -
Value Error trying to get data from mysql in django
I'm running a django app and ive implemented mysql. When i run the server and try to load the page i get the error "badly formed hexadecimal UUID string." This occurs in the uuid.py file in init at line 140 and from what i can tell, this occurs because the value hex is not of length 32 but i dont know how to address this issue. This is the model that the entries in the database follows. from django.db import models import uuid from django.db.models import ( UUIDField, CharField, TextField, IntegerField, DecimalField, ImageField ) # Create your models here. class AnimeCatalog(models.Model): anime_id = UUIDField(primary_key = True, default=uuid.uuid4, editable=False) name = CharField(max_length=300) genre = CharField(max_length=300) typeanime = CharField(max_length = 10) episodes = IntegerField(default=0) rating = DecimalField(max_digits = 4, decimal_places = 2, null = True) members = IntegerField() anime_cover = ImageField(blank = True, null = True, upload_to = "img/animeCover", verbose_name = "Profile Photo") Then I try to call the objects.all() method on this model to retrieve it from mysql in the views.py file which is below from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.views import View from .forms import AnimeCatalogForm from .models import AnimeCatalog from .WebScraping import findAnimePic import …