Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Q lookup search in title for strings from a list returns duplicates
sorry if my question is weird or incoherent. What I'm trying to do is this: I take the string that the user has typed out as his search input and create a list of strings from that input, and then create a loop that goes over the list and searches for each item in that list in database, let me make it a bit clearer with some code: #I take the string that the user inputs as his search query = request.GET.get('q') # I create a list by spliting the original search string query_srch = query.split() # Create a list which will later hold the items returned by the db lookup searchnews = [] #start the loop to lookup for word in query_srch: if word: searchnews += NewsPost.objects.filter( Q(title__icontains=word) ).distinct().order_by('-date') The reason why I do this is because if the title of an article in your website is "Obama: blablabla", but the user searches for "Barack Obama", the article "Obama: blablabla" will not actually come up at all. The problem is that when I do this for loop search thing, if my search query is "Obama Obama Obama", I will get a list with each article not duplicated but triplicated … -
Django - Show updated session variables in template
I'm trying to be as concise as possible in this post because I have another detailed post that has not received answers yet (trying to stay more conceptual in this post): Return updated session variables (while page is loading) through Ajax call using Django I want my webpage to load updated session variables into my index.html template while those session variables are updated server side. Currently, not until after an HttpResponse has been rendered by my view do I have access to the updated session variables. Is there a way in Django to make updated session variables available to the client before the HttpResponse is rendered? These bits of code / settings are not working to make this happen: settings.py SESSION_SAVE_EVERY_REQUEST = True views.py request.session.modified = True request.session.save() -
Save user Graphql Apollo Client
I am trying to save a user id to a new biz. I keep getting a 400 error and can not figure out why. I am using django for the backend with graphql and apollo client for the front with vue js. On my request the user ID is sent but for some reason throws a 400 bad request error. Create Biz Mutation Apollo export const CREATE_BIZ_MUTATION = gql` mutation CreateBizMutation($name: String!, $owner: ID!) { createBiz(name: $name, ownerId: $owner) { name } }` Create Biz mutation Django class CreateBiz(graphene.Mutation): id = graphene.Int() name = graphene.String() code = graphene.String() owner = graphene.Field(UserType) class Arguments: name = graphene.String() def mutate(self, info, name): user = get_user(info) or None code = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(6)) biz = Biz( code = code, name = name, owner = user ) biz.save() return CreateBiz( id= biz.id, name = biz.name, code = biz.code, owner = biz.owner ) Create Biz Component createBiz () { const owner = localStorage.getItem(DJANGO_USER_ID) if (!owner) { console.error('No user logged in') return } const { name } = this.$data this.$apollo.mutate({ mutation: CREATE_BIZ_MUTATION, variables: { name, owner } }).catch((error) => { console.log(error) }) } } -
Django 1.11: combine fields for QuerySet using Q
I'm using the DataTable Plugin to render a list of reference for "nanas" (spanis for babysitters). Right now I can filter on: nana's nombre(name) or reference's nombre(name). In adition to this I want to filter on nana's nombre + nana's apellido_paterno Doing this doesn't work: if search_value: queryset = queryset.filter( Q(nana__nombre__icontains=search_value) & Q(nana__apellido_paterno__icontains=search_value), Q(nana__numero_de_documento__exact=search_value) ) Model: class Referencia(models.Model): nombre_apellido = models.CharField(blank=False, null=False, max_length=200) telefono = models.CharField(blank=False, null=False, max_length=15) correo = models.EmailField(blank=True, null=True) direccion = models.TextField(blank=True, null=True) estado_referencia = models.IntegerField(blank=False, null=False, choices=ESTADO_REFERENCIA, default=0) nana = models.ForeignKey(Nana) comentario = models.CharField(blank=True, null=True, max_length=400) def query_referencia_by_args(**kwargs): draw = int(kwargs.get('draw', None)[0]) length = int(kwargs.get('length', None)[0]) start = int(kwargs.get('start', None)[0]) search_value = kwargs.get('search[value]', None)[0] order_column = kwargs.get('order[0][column]', None)[0] order = kwargs.get('order[0][dir]', None)[0] order_column = ORDER_COLUMN_CHOICES[order_column] # django orm '-' -> desc if order == 'desc': order_column = '-' + order_column queryset = Referencia.objects.all() total = queryset.count() if search_value: queryset = queryset.filter( # Q(nombre_apellido__icontains=search_value) | Q(nana__nombre__icontains=search_value) | Q(nana__apellido_paterno__icontains=search_value) | Q(nana__numero_de_documento__exact=search_value) ) count = queryset.count() queryset = queryset.order_by(order_column)[start:start + length] return { 'items': queryset, 'count': count, 'total': total, 'draw': draw } -
How to log GET/POSTS requests to a localfile?
I want to log the below data which is printing on console to local file. The below data is the GETS and POSTS of the apps of website and its printing on the console. I want to write it to a local log file. I am new to Django. Anyone Please guide me. [08/Jan/2018 22:25:05] "GET / HTTP/1.1" 200 5533 [08/Jan/2018 22:25:05] "GET /static/personal/css/bootstrap.min.css HTTP/1.1" 304 0 [08/Jan/2018 22:25:05] "GET /static/personal/img/logo.jpg HTTP/1.1" 304 0 [08/Jan/2018 22:25:05] "GET /static/personal/img/img_avatar2.png HTTP/1.1" 304 0 [08/Jan/2018 22:25:08] "GET /blog/ HTTP/1.1" 200 1909 [08/Jan/2018 22:25:11] "GET /contact/ HTTP/1.1" 200 1833 [08/Jan/2018 22:25:13] "GET / HTTP/1.1" 200 5533 I am using the below logging file. Am i proceeding in the right way or not. Please Guide me Thank you in advance. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { # Log to stdout 'level': 'INFO', 'class': 'logging.StreamHandler', }, 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': os.path.join(LOG_DIR, 'django_debug.log'), } }, 'root': { # For dev, show errors + some info in the console 'handlers': ['file'], 'level': 'INFO', }, 'loggers': { 'django.request': { # debug logging of things that break requests 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, }, } -
Django scheduler like facebook post schedule
What is the best way to schedule like a facebook post schedule in django ? Any idea or example can you guys give me ? -
RelatedObjectDoesNotExist at /admin/login/ User has no scuser
I have another site that I created which does not have this problem and is to the best of my knowledge setup the same way. Here is my models.py from the users app: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from users.choices import * from django.db.models.signals import post_save from django.dispatch import receiver from listings.models import University # Create your models here. class SCUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50,blank=False,default='User') join_date = models.DateTimeField(default=timezone.now) university = models.ForeignKey(University,related_name='u_university',null=False,blank=False) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: SCUser.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.scuser.save() Here is the error: RelatedObjectDoesNotExist at /admin/login/ User has no scuser. Here is the traceback: Internal Server Error: /admin/login/ Traceback (most recent call last): File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 393, in login return LoginView.as_view(**defaults)(request) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/utils/decorators.py", line 67, in _wrapper return bound_func(*args, **kwargs) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper … -
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 …