Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model + Flask API
I’m working on creating a RESTful CRUD API for an application I’m working on - and I’m looking to get Django and Flask talking to the same table in a standard SQLite database. Say if I had a standard Django Todo Model - is it possible to mimic the same model with Flask (create the class etc etc) and then use SQL alchemy to hit the same table...? Has anyone else achieved such a thing? Any pitfalls or issues with such a method? -
How to handle Python's stack overflow error in Django?
I have created a Django project and a command in it that is looping functions. It is small site scrapper going through a site api and finding data and circling back to the api link. import json from time import sleep import httplib2 from django.core.management import BaseCommand from project.models import Writers class Command(BaseCommand): help = "scraper" page = 1 max_pages = 10000 ids = [] def handle(self, *args, **options): self.process() def process(self): try: if self.page >= self.max_pages - 10: self.check_for_last_page() self.get_data() except Exception as e: print(e) sleep(15) self.process() def check_for_last_page(self): url = "https://example.com/api/page/latest" http = httplib2.Http() try: _s, _r = http.request(url.format(self.page)) if int(_s.get('status')) == 200: b = json.loads(_r) self.max_pages = int(b.get('last_page')) else: sleep(10) self.process() except Exception as e: print("Exception found in 'check_for_last_page' ==> {}".format(e)) def get_data(self): url = "https://example.com/api/page/{}".format(self.page) print("\nChecking page {} ".format(self.page)) http = httplib2.Http() try: _s, _r = http.request(url) if int(_s.get('status')) == 200: data = json.loads(_r) for d in data: self.ids.append(d[0]) self.get_data_info() else: print("Get data response is not 200. Sleeping for 10 seconds!") sleep(10) self.get_data() except Exception as e: print("\tException found in 'get_data' ==> {}".format(e)) if self.page > 10: self.page -= 10 else: self.page = 0 self.ids = [] self.process() def get_data_info(self): url = "https://example.com/api/data/{}" http = httplib2.Http() … -
Calling script in included template violates CSP?
In Django, I want to include some templates dynamically like so <li class="divider"></li> {% for tab, content in tabs.items %} {% include tab.TEMPLATE %} {% endfor %} <br><br> This is all jolly good, but in one of these templates I need to call a very short snippet of script. One line! I knew that my CSP would block inline scripts like this: <script> $('#modal-body').html( $('#about-the-data-content').css('display', '') ); <script> => Refused to execute inline script because it violates the following Content Security Policy directive: "default-src *". Either the 'unsafe-inline' keyword.... I did not expect that I would get the same error if I moved that one line of script to a separate file and tried to include it like so: <script src="{% static 'js/assessor/v2/modal-setup.js' %}"></script> Here, I get the same error about refusing to execute inline scripts. But this script isn't inline... or is it? Any discussion or suggestions appreciated! Worst case, I guess I'll set up a nonce? -
How can the Python Image module be changed to address multiple versions of Django?
When I pip install the Image module for Python 3, the installation works fine. When I pip install the Image module for Python 2, the installation breaks: Collecting pyprel Downloading pyprel-2018.1.8.2203.tar.gz Collecting Image (from pyprel) Downloading image-1.5.17-py2.py3-none-any.whl Collecting numpy (from pyprel) Downloading numpy-1.14.0-cp27-cp27mu-manylinux1_x86_64.whl (16.9MB) 100% |████████████████████████████████| 16.9MB 79kB/s Requirement already up-to-date: pyfiglet in /usr/local/lib/python2.7/dist-packages (from pyprel) Requirement already up-to-date: shijian in /usr/local/lib/python2.7/dist-packages (from pyprel) Collecting pillow (from Image->pyprel) Downloading Pillow-5.0.0-cp27-cp27mu-manylinux1_x86_64.whl (5.8MB) 100% |████████████████████████████████| 5.9MB 230kB/s Collecting django (from Image->pyprel) Downloading Django-2.0.tar.gz (8.0MB) 100% |████████████████████████████████| 8.0MB 154kB/s Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-DZf02T/django/setup.py", line 32, in <module> version = __import__('django').get_version() File "django/__init__.py", line 1, in <module> from django.utils.version import get_version File "django/utils/version.py", line 61, in <module> @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-DZf02T/django/ This may be because recent Django versions may no longer supporting Python 2, as suggested here. Is this actually the cause of the problem? I want to advise the relevant developers on what to do to fix the pip installation, perhaps by suggesting a Django version requirement, but I don't know … -
Django LiveServerTest and javascript : how to let user enter confirmation?
using Django and LiveServerTest, I am testing this url : #template.py <div id = "id_delete"><a href="/{{ file.pk }}/delete/" onclick="return confirm('Are you sure ?')">delete</a></div> #tests.py self.selenium.find_element_by_xpath('//*[@id="id_delete"]/a').click() and I wish Selenium to pause to let me click on "cancel" when javascript asks 'Are you sure ?' and go on with the following tests. -
Is Cloud firestore the right solution for me?
I am building a website+ mobile app. content will have text, image and videos. will be developed in python django + reactjs and react native.+ GraphQL Can I use cloud firestore for this? Can I host my django website in Cloud firestore using its cloud functions and scale with videos and images stores in clooud firestore storage? Is Cloud Firestore right solution for this, or should I use Google App Engine or Google Compute engine? Thanks, -
Does Django support setting the beginning value for an id column?
I have seen several questions and answers on SO, most were three years old or older and I looked at the Django documentation. I have to have a 9+ digit number for an id. Most responses were to do this at the database. I am guessing that means to create the model in Django and then go back to the database and change the id column Django created with a new starting/next value attribute on the column. If not how can I create a database table from Django, Code First, that allows me to create a table with an id column that starts at 100000000? And, it be done with the stock model object methods in Django. I don't really want to do a special hack. If that is the case, I can go the database and fix the column. I was trying to adhere to the Code First ideas of Django (though I prefer database first, and am afraid using inspectdb will make a mess.) -
Linking one models with a set of another in Django
I am currently working on developing a database and api system where users can create a portfolio which contains a list of coins. I am using django and I searched everywhere but i kept seeing foreign keys but im not sure thats what I need in this situation. I want two models, one for portfolios which a user will be able to query on, and another coin model which the user will be able to also query on. However in the portfolio there should be a list of coins. I know how to do this in Java using objects but not sure the method in django. Here is my model class: from django.db import models class Portfolio(models.Model): name = models.CharField(max_length=250) def __str__(self): return self.name class Coin(models.Model): name = models.CharField(max_length=100) symbol = models.CharField(max_length=5) price = models.DecimalField(max_digits=20, decimal_places=9) info = models.TextField() website = models.TextField() rank = models.IntegerField() def __str__(self): return self.name + " - " + self.symbol Now i would ideally have something like coins = list of Coins model if I was using java to make the objects, but since this is for a database and in Django, im not sure how I should link the two. I've seen related objects … -
can't display a value in the template
I am having trouble displaying the value on the html template from the mysql database. my view: from django.contrib.auth.decorators import login_required from django.db.models import Count, Min, Sum, Avg, Max from .models import Gwtable import datetime def index(request): max_value = Gwtable.objects.all().aggregate(Max('salesprice')) my html: {{ max_value.values|floatformat:2 }} -
Change field type in model serializer without changing model
I have a model with a string field with a corresponding model serializer. I'd like to change the serializer so that it now takes a list of strings for that field, but converts that list to a string internally. Basically, internal_repr = input.join(',') I've tried changing the data type in the validate function, but I still get a validation error that it's not a string. Where should this change occur? Is it also necessary to override the serializer on that field to a ListSerializer with child=CharField specified? -
Display localized date with just month and day in a Django template
I want to display a localized date in a Django template with just the month and the day. I currently have {{ value|date:"b d" }} This will display "jan 8" no matter the current locale. So even in french I'll get "jan 8" instead of "8 jan". How can I have it to work correctly for any locale? -
ajax, vanilla javascript, django, views
I want to get ajax response without jquery(regular javascript only). I'm getting whole html page. I need only string from views.py function. file.html: ... <form method="post" > ... <input type="submit" value="Send" id="button"> ... <script type="text/javascript" src="{% static 'js/main.js' %}"></script> <script> var el = document.getElementById("button"); el.addEventListener('click', mainik); </script> main.js: function mainik(e){ e.preventDefault(); XMLHttpRequest.onreadystatechange = backgroundfunc; XMLHttpRequest.open("GET", "/change"); function backgroundfunc() { if (XMLHttpRequest.readyState === XMLHttpRequest.DONE && XMLHttpRequest.status === 200) { console.log(XMLHttpRequest.responseText); } } } XMLHttpRequest.send(); views.py : ... def home(request): ... return render(request,file.html,{}) def back(): heh = "myresp" return HttpResponse(json.dumps(heh)) // I need "myresp" on the screen In Network Monitor I see that url /change works, but response is whole html file instead "myresp" text. I saw some examples with jquery but I can't modify them that would help in my case. I didn't use jquery. I am totally beginner. Please be patient. Thank You : ) -
TypeError: __init__() missing 1 required positional argument: 'on_delete'
Hi i'm trying to run my code and im getting this error: File "C:\Users\JOSHUA\Documents\ypgforum\myproject\boards\models.py", line 13, in <module> class Topic(models.Model): File "C:\Users\JOSHUA\Documents\ypgforum\myproject\boards\models.py", line 16, in Topic board = models.ForeignKey(Board, related_name='topics') TypeError: __init__() missing 1 required positional argument: 'on_delete' Meanwhile this is the models.py it pointed to; class Topic(models.Model): subject = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, related_name='topics') starter = models.ForeignKey(User, related_name='topics') last_updated = models.DateTimeField(auto_now_add=True) -
Relate model to python object
I have some code in which I have defined some Python models. For example: class Store(object): ''' The store object... Should it be a Django model? ''' def __init__(self, *args, **kwargs): self.name = kwargs['name'] self.id = kwargs['id'] def __str__(self, *args, **kwargs): return self.name kittenstore = Store(name='kittenstore', id=1) dogstore = Store(name='dogstore', id=2) stores_list = [kittenstore, dogstore] class Stores(object): def __init__(self, *args, **kwargs): self.stores = stores_list def get_choices(self): store_choices = () for store in self.stores: store_choices+= ((store.id, store.name),) return store_choices I'd like to refer to those stores from another Django model. I could use a models.Integerfield with choices=get_choices(), but when I filter in a related models, then I always get the id back and I need to find the correlating store if I want to use it in my code. Is there not a (python) trick to get back the Store object instead of the id? Maybe with a custom Field? -
API RESTful Resource Naming
I always have the doubt that you can see below when i need to create theresource URLs for a REST API. I wonder if some one can help me. Let's suppose that i have two models. User Post User can submit his own posts and can comment his own and another posts. Main resources URLs for User would be: GET /users # Retrieve all users. POST /users # Create a new user. GET/DELETE/PUT /users/{user_id} # Get, remove and update an user. Main resource URLs for Post would be: GET /posts # Retrieve all posts. POST /posts # Create a new post. GET/DELETE/PUT /posts/{post_id} # Get, remove and update a post. My problem come when for example i want: Top 10 submitters (filter for a parameter(external link, discussion, all)). The URL should be: GET /users/top?type=ext GET /users/top?type=disc GET /users/top # for all Or maybe it should be: GET /users?top=ext GET /users?top=disc GET /users?top=all The same but with posts: Top 10 commented post (filter for a parameter(external link, discussion, all)). The URL should be: GET /posts/comments?type=ext GET /posts/comments?type=disc GET /posts/comments # for all Or maybe it should be: GET /posts?top=ext GET /posts?top=disc GET /posts?top=all Any of above options are good for you … -
how to do a pagination-django with variable 'per_page'?
how to do a pagination with variable 'per_page'. For example, I have 100 articles I wish that the first page (1) contains 3 articles, the second page (2) contains 5 articles, will excite, me who draws of how many articles in each page. see the picture. -
I got the following error while trying to push my Django app to Heroku: TomlDecodeError("Invalid date or number")
When I git push my Django app to Heroku, I get the error below. How do I know what needs to be changed in my code from this error? I'm not sure which date information I misconfigured to raise this error. If you could point me in the right direction, that would be great! remote: File "/tmp/build_913f5397888fc6f8943894f7ab01ea65/.heroku/python/lib/python3.6/site-packages/pipenv/vendor/toml.py", line 454, in _load_line remote: raise TomlDecodeError("Invalid date or number") remote: toml.TomlDecodeError: Invalid date or number remote: ! Push rejected, failed to compile Python app. Here is the full traceback error below: :\Users\Jup\Drop>git push heroku master Counting objects: 19, done. Delta compression using up to 4 threads. Compressing objects: 100% (15/15), done. Writing objects: 100% (19/19), 8.93 KiB | 0 bytes/s, done. Total 19 (delta 8), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! The latest version of Python 3 is python-3.6.4 (you are using python-3.6.3, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3.6.4). remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing requirements with latest Pipenv… remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.6/site-packages/pipenv/project.py", line 272, in parsed_pipfile remote: return contoml.loads(contents) remote: File "/tmp/build_913f5397888fc6f8943894f7ab01ea65/.heroku/python/lib/python3.6/site-packages/pipenv/patched/contoml/__init__.py", line … -
ManagementForm data missing when saving intermediate M2M table
ManagementForm data missing error while formset validation I get this error when I try to save a parent form with intermediate m2m table child formset. I don't know how to solve because the lack of information about this error in Traceback. Please help! models.py class Material(models.Model): name = models.CharField(max_length=200) familiy = models.ForeignKey(Material_family, on_delete=models.CASCADE, null=True) … class Purchase(models.Model): number = models.IntegerField() date = models.DateField() … class Purchase_detail(models.Model): material = models.ForeignKey(Material, on_delete=models.CASCADE) purchase = models.ForeignKey(Purchase, on_delete=models.CASCADE) quantity = models.IntegerField() unit_value = models.IntegerField(default=0) forms.py class PurchaseModelForm(forms.ModelForm): class Meta: model = Purchase fields = (‘number’,’date’ , ’…’) def __init__(self, *args, **kwargs): super(PurchaseModelForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.form_id = 'id-purchase-form' self.helper.form_method = 'post' class Purchase_detailModelForm(forms.ModelForm): class Meta: model = Purchase_detail fields = ('material','quantity','unit_value') def __init__(self, *args, **kwargs): super(Purchase_detailModelForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.form_id = 'id-purchase-form' self.helper.form_method = 'post' self.helper.form_class = 'form-inline' self.helper.field_template = 'bootstrap3/layout/inline_field.html' DetailFormSet = forms.inlineformset_factory(Purchase, Purchase_detail, form=Purchase_detailModelForm, extra=1) views.py def purchase_new(request, purchase_id=None, *args, **kwargs): template = 'erp/purchase_form.html' if purchase_id: inst = Purchase.objects.get(pk=purchase_id) else: inst = Purchase() if request.method == 'POST': form = PurchaseModelForm(request.POST or None, request.FILES, prefix='purchase', instance=inst) formset = DetailFormSet(request.POST or None, request.FILES, prefix='detail') form_valid = form.is_valid() if form_valid: purchase = form.save() formset.save(commit=False) for … -
Django - DateTimeField query on SQLite vs MySQL
This query returns an empty QuerySet in MySQL, but works in SQLite: commented_this_month = Post.objects.filter(comment__created__month=now.month) My models are really simple: class Comment(models.Model): comment = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(default=timezone.now) post = models.ForeignKey(Post, on_delete=models.CASCADE) Is there something I am missing? -
Costumize django admin dashboard
In Django 1.11 it's possible customize the dashboard of admin area (index page)? I need to show some table of data or graph. I've tried to override index() method ma it doesn't work. class MyAdminSite(): def index(self, request, extra_context=None): extra_context = extra_context or {} extra_context["test"] = "test" return super(MyAdminSite, self).index(request, extra_context) -
Modify a File with Pillow than save it in database, modifing his attributes first
I'm saving the original file logo = CompLogo(logo=form.cleaned_data['logo'], company=obj) logo.save() my_task.delay(logo.logo.path, obj.pk) then I get the image from the storage using a celery task @task def my_task(path,id): img = crop_image(path) an obtain a new image: def crop_image(path): image = Image.open(path) image_clone = image.copy() image_clone.thumbnail((100, 100)) return image_clone I want to get the new image file and saved in the database but before saving modify his filename. CompLogo.objects.create(logo=crop_image(path), obj_id=obj_id) The above line is not working, I can't change the filename. -
How to use filter in Count Q in Django
I'm trying to sort a query set by its foreign key's number of objects that has been created in the last 7 days. As in if there are three titles like: Title one --> total entry: 100, entries in last 7 days: 5 Title two --> total entry: 10, entries in last 7 days: 8 Title three --> total entry: 50, entries in last 7 days: 2 I want them ordered like: Title two > Title one > Title three This is what I'm trying to get the above generator: all_titles = Title.objects.annotate( num_entries=Count( "entry", filter = Q(entry__entry_date2__gte=make_aware( datetime.datetime.today()-datetime.timedelta(days=7) ) ) ) ).order_by("num_entries") This is what my models look like: class Title(models.Model): title_text = models.CharField(max_length=50, null=True) title_url = models.CharField(max_length=100, null=True) title_channels = models.ManyToManyField(TitleChannels) def __str__(self): return self.title_text class Entry(models.Model): entry_title = models.ForeignKey(Title, on_delete=models.CASCADE) entry_text = models.CharField(max_length=2500, null=True, blank=True) entry_author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) entry_date = models.CharField(max_length=20, null=True, blank=True) entry_points = models.IntegerField(default=0, null=True, blank=True) entry_readability = models.BooleanField(default=True) entry_date2 = models.DateTimeField(null=True, blank=True) def __str__(self): return self.entry_text Instead of ordering it by what I want, I'm getting a list that is sorted by Titles entry_set's length. -
Share image on instagram from Django template
I want to share image on instagram from Django template by using 'image.url'. I have used 'django-social-share' to share image on facebook and twitter. Is there any similar package from which I can share image on instagram? -
Allow user to select random blog bost
I've started using Django 2.0 and Python 3.6.3 to develop a website which will display customized "Posts", as in a blog Post. I want the user to be able to click a button that basically says "Random Post". This button will take them to a template which loads a random blog post. Here's my Post model: class Post(models.Model): post_id = models.AutoField(primary_key=True) ... other fields ... other fields def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Here are some relevant views: class PostListView(ListView): model = Post template_name = 'blog/post_list.html' class PostDetailView(DetailView): model = Post template_name = 'blog/post_detail.html' Here is my problematic view: import random def random_post(request): post_ids = Post.objects.all().values_list('post_id', flat=True) random_obj = Post.objects.get(post_id=random.choice(post_ids)) context = {'random_post': random_obj,} return render(request, 'blog/random_post.html', context) Here I am trying to create a Values List of all post_id values for the Post model. Then I'm trying to get a random choice from this Values List, which would be a random id. Then I'm trying to create a context and render a template using this logic. Here are relevant urlpatterns: urlpatterns = [ path('post/<int:pk>/', views.PostDetailView.as_view(),name='post_detail'), path('post/random/<int:pk>', views.random_post, name='random_post'), Needless to say this is not working. If I leave off the "int:pk" it renders a blank … -
RedirectView.as_view not working at the root
In a django 1.8 project, I am attempting to redirect http://myProject/ads.txt to an external url http://a.location.that.has.the.ads.txt.file and thus serve the ads.txt file without using ftp to simply place the ads.txt in the root. Given this minimal directory structure: django projects myProject myapp urls.py views.py someotherapp yetanotherapp myProject settings.py urls.py (this is the top urls.py) views.py in myProject/myProject/urls.py, (the “top” urls.py) I have as the first entry in the urlpatterns list, the lines: urlpatterns = patterns('', (r'^ads\.txt', RedirectView.as_view(url=http://a.location.that.has.the.ads.txt.file', permanent=False)), followed by many more pattern matching regex’s. This does not work and fails with a 404. What does work is urlpatterns = patterns('', (r'^foo/ads\.txt', RedirectView.as_view(url=http://a.location.that.has.the.ads.txt.file', permanent=False)), and then calling http://myProject/foo/ads.txt Unfortunately, ads.txt files must be placed at the site root. I have tried many different regex’s that test fine in a regex validator, but just don’t work (returns 404). How do I do this without the extra dir “foo”? Any thoughts appreciated. Thank you.