Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Circular import error after enabling i18n
After enabling i18n in my project, circular import errors started to appear, LANGUAGE_CODE = 'en' LANGUAGES = [ ('en', 'English'), ] USE_I18N = True on USE_I18N = False everything works fine. Django 1.16.11 DjangoCMS 3.2.5 At first started to fixing imports, but there is too many files... Any ideas? -
My custom django-admin command won't call celery task
I am trying to write a custom django-admin command that executes a celery task, however the task doesn't execute and django just hangs when I try. from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): print "starting task" my_celery_task.delay() print "task has been sent" The output I receive when calling the command is: starting task I never reach the "task has been sent" line. It just hangs. I'm not sure why the task isn't running. Celery tasks are called perfectly when called by a view. -
Django + ajax dynamic table content rotation
This is the second question in the row about my Django project. The code I use here is partly copied from this question:Stack Overflow What I aim to achieve is a dynamic table, that loops through objects in a list. Let's say I have 21 records. The table first displays records of 1 to 10, on the displaykala.html table. Then it replaces only the table content with records of 11 to 20(with AJAX, without page refresh. The new contents come from get_more_tables_kala.html, and those table rows coming from there, are appended to the displaykala.html table). At no point should the table be empty (UNLESS there is simply no objects to display). Basicly it always displays first ten records(even if there is only one). Then the code increments the startindex and endindex of the rows, and checks if there is records between those. If there is more than 10 records, it will empty the table and instantly load up the next records (as long as there is even 1 record). Else, the program should wait X amount of seconds, until checking again. The code has been going through various experimentations, I'm sorry for any dumb coding. I'm still learning Django and … -
Python - Compare birthdate
I have 2 variables which are 2 birthdates. I want to compare both for displaying a message telling 'Hey it seems you have almost the same age !" try : his_birthdate = player.profile.birthdate my_birthdate = request.user.profile.birthdate except: pass Well... I think if both persons are maximum 3 years of difference, we can considere that they have almost the same age. So I can do many conditions like this if you know what I mean : try : his_birthdate = player.profile.birthdate my_birthdate = request.user.profile.birthdate if his_birthdate > my_birthdate + 3: .... if his_birthdate > my_birthdate - 3: .... except: pass But I think there is a better solution ? Thanks for your help ! -
Django How can i split string using template tag
Hello I want to know that how can I split string of dictionary values This is my crawler which is returns dictionary data looks like data = { {0 'http://..., product name, product price'} {1 'http://...2, product name2, product price2'} n. {n 'http://...2, product name2, product price n'} } I want to split these data by comma like, for value in data.values(): href, product_name, product_price = str(value).split(",") in Django This is my crawler.py import requests from urllib import parse from bs4 import BeautifulSoup def spider(item_name): url_item_name = parse.quote(item_name.encode('euc-kr')) url = 'http://search.11st.co.kr/SearchPrdAction.tmall?method=getTotalSearchSeller&isGnb=Y&prdType=&category=&cmd=&pageSize=&lCtgrNo=&mCtgrNo=&sCtgrNo=&dCtgrNo=&fromACK=recent&semanticFromGNB=&gnbTag=TO&schFrom=&schFrom=&ID=&ctgrNo=&srCtgrNo=&keyword=&adUrl=&adKwdTrcNo=&adPrdNo=&targetTab=T&kwd=' + url_item_name resp = requests.get(url) resp.raise_for_status() resp.encoding='euc-kr' plain_text = resp.text soup = BeautifulSoup(plain_text, 'lxml') mytag = soup.find_all(True, {"class": ["sale_price", "list_info"]}) #for link in soup.select('div.list_info p.info_tit a') : data = {} count = -1; for link in mytag: if(link.find('a')): count+=1 href = link.find('a').get('href') product_name = link.find('a').string data[count] = str(href) + ", " + str(product_name) else: product_price = link.string if(product_price): data[count] = data[count] +", " + str(product_price) for value in data.values(): print(value) resp.close() return data and this is my views def post_shop_list(request): posts = spider("product name") return render(request, 'blog/post_list.html',{'posts' : posts}) and this is my post_list.html {% for key, value in posts.items %} <div> <td>{{key}}</td> <p>product name :{{value}}</p> <h1><a href=href> </a></h1> … -
Print out a list of items with Django
I'm developing a Django project and i'm trying to solve an issue. My main scope is getting a JSON file through a url and print out the data into a table(HTML). To be more clearly, i got an Object like referred below and every record i would like to printed into my table. { "myData": [{ "name": "John", "surname": "Williams", "birthday": "05/12/1997", }, { "name": "John", "surname": "Williams", "birthday": "05/12/1997", },]} <table class="table table-striped table-hover table-bordered"> <thead class="thead-dark"> <tr> <th>First Name</th> <th>Last Name</th> <th>Birth Day</th> </tr> </thead> <tbody> {% for myData in range(20) %} <tr> <td> {{ myData.name }} </td> <td> {{ myData.surname }} </td> <td> {{ myData.birthday }} </td> </tr> {% endfor %} </tbody> </table> I find it as a very common implementation but still i can't find a solution. Also when i'm trying to run the code below inside my views.py file everything works great but If i'm trying to send data into an .html file i got multiple errors. for i in range(5): print ada[i] The first one when i wrote {% for x in range(20) %} I got this error : Could not parse the remainder: '(20)' from 'range(20)' Then I'm trying to pass range(20) as … -
python language change telegram-bot
I have any trouble: I write telegram-bot on Python+django by helps python-telegram-bot. In this bot me need trigger between languages and I stuck(( I have keyboard: def get_language(self): keyboard = [[u"Русский"], [u"English"]] return ReplyKeyboardMarkup(keyboard, resize_keyboard=True) And I have hadler: elif state == LANGUAGE_WAIT_STATE: if text == u"Русский": profile = Profile.objects.get(telegramid=chat.profile.telegram_id) profile.locale = "ru" profile.save() chat.state.set(MENU_WAIT_STATE) chat.send_message(chat.l(u"WELCOME_MESSAGE"), keyboard=keyboard.get_menu()) elif text == u"English": profile = Profile.objects.get(telegram_id=chat.profile.telegram_id) profile.locale = "en" profile.save() chat.state.set(MENU_WAIT_STATE) chat.send_message(chat.l(u"WELCOME_MESSAGE"), keyboard=keyboard.get_menu()) else: chat.send_message(chat.l(u"USE_MENU")) This handler catch what button pushed and change profile.locale in DB. It's works. profile.locale is changing. But..... Labels on buttons don't changes, without "/start". Although all chat messages change their locale. But not buttons( I catch, what buttons pressed by "keyboard.BACK_BTN.text" and not understand what's wrong. What I must doing with it??? How to refresh button-labels without "/start"? -
Django - prefetch_related isn't working
I can't find a way to reduce a number of queries in my view/template. There is a Trip model which has a foreign key to City and the City has many GoogleApiCityCache objects - so GoogleApiCityCache has a foreign key to City. The important thing is that GoogleApiCityCache stores a formatted_address of the City object. I'm trying to prefetch GoogleApiCityCache to prevent querying database in each loop but according to Django-debug-toolbar, it access the database in every iteration. As you can see I'm trying to prefetch city__city_caches (city_caches is the related name) in TripManager's get_queryset method. And I'm trying to do the same thing in a view. None of them works. Please, note that city.formatted_address get one of it's city_caches which stores the formatted_address This is a structure: class TripManager(models.Manager): def get_queryset(self): return super(TripManager,self).get_queryset().prefetch_related('city__city_caches') .... def ordered_by_date_to_reverse(self): queryset = self.get_queryset() return queryset.order_by('-date_to') class Trip(models.Model): user = models.ForeignKey('auth.User', related_name='trips') city = models.ForeignKey('locations.City', related_name='trips') date_from = models.DateField() date_to = models.DateField() detail = models.TextField(null=True, blank=True) objects = TripManager() City model property: @property def formatted_address(self): return self.get_cache_by_lang().formatted_address This is a view: def profile(request, slug): owner = User.objects.filter(userprofile__slug=slug).prefetch_related('trips__city__city_caches').first() return render(request, 'profiles/profile/profile.html', {'owner': owner}) The problematic part of template: {% for trip in owner.trips.ordered_by_date_to_reverse %} {{ … -
PostgreSQL + Django AutoField id doesn't get restarted after flush
I am currently testing Django project using django-nose. I use PostgreSQL for my DB. The problem I am facing is: In test setUp method I create one Emp instance and save it. Then I execute this: Emp.objects.filter(empId=1) but this doesn't exist. During debugging I figured that the Emp instance exists in DB but its ID is 137. I presume that is the issue with django-nose as it flushes DB after every test, however previous empId's seem to remain. Note: I am using: class Emp(models.Model): empId = models.AutoField(primary_key=True) My question is, how do I resolve this issue? Is there a way to restart id auto-increment routine after every setUp call? -
Get and subscribe value from another model in case of ManyToManyField
I want to get value from foreign key from another model and subscribe it. It works when field is declared as ForeignKey but when field is declared as ManyToManyField it not works. How can I do it? Please help. class Document(models.Model): project = models.ForeignKey(Project) text = models.ForeignKey(Text, null=True, blank=True) language = models.ManyToManyField(Language, null=True, blank=True) def save(self, *args, **kwargs): self.text = self.project.text #WORKS self.language = self.project.language.all() #NOT WORKS super(Document, self).save(*args, **kwargs) -
Django saving to public media folder , error 403
So i have Angular + Django REST API applications hosted on nginx + gunicorn setup. I'm facing a weird problem . I have my media folder permisssions set to 777 and in my nginx config: location /media { alias /home/shalin95/zona_project/zona_api/media; expires 20m; } I have a model Product with main_picture field ( ImageField saving the files to /media/photos/) . When i create new instance ( new product ), and sometimes when i want to open the image in the browser i get 403 Forbidden error. NOTE: This happens occasionally , not on every instance saved ( no specific pattern , just randomly) Thank if i go and chmod -R 777 the media folder everything is okay ( i can see the picture ) , but why this happens ( on some occasions ) ? -
Trouble in learning Django
I'm learning Python Django, but I find it difficult to understand.but i need to learn it. I tried to learn from codingforentrepreneurs.com, www.lynda.com, and https://stackskills.com they all is very good recources but i didnt understand it. Can you help us with how can i learn it ? Knowing that i'm PHP developler but i must change to Django. -
Django Rest Framework HTTP Post Calls and Authentication with Ionic Framework
I implemented the Django Rest Framework into my Django project so I could use Django as a backend to my Ionic Framework app while maintaining the web app that I can make with Django. I went through the process to OAuth2, using the oauth toolkit, but now I am unsure on how to make the http request calls from the ionic framework side to authenticate a user and get a token. So far on the Ionic side I have the http request as: login(username, password, url) { let headers = new Headers() headers.append("Content-Type", "application/x-www-form-urlencoded"); return this.http.post(url, {"username": username, "password": password, }, {headers: headers}) .map(res => res.json()); } But when I run it in my browser, I get No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 500. On the server side the curl command curl -X POST -d "grant_type=password&username=USERNAME&password=PASSWORD" -u "CLIENT ID:CLIENT SECRET" https://www.example.com/o/token/ works perfectly fine and returns a token, where USERNAME, PASSWORD, CLIENT ID, and CLIENT SECRET are all the respective values. I'm not sure if this is the right question, but how do I turn the cURL command into something I can use in … -
How can i pass data from django template to angular 4?
I am having angular 4 application integrated with django. Angular 4 is just for showing some data in django template and i am having some RESTful api in django.I have used webpack to compile .ts files to js and included in django templates.I am getting the angular content in django templates and it works fine. I am having angular component code import { Component,OnInit } from '@angular/core'; import {Http, Response} from '@angular/http'; @Component({selector: 'my-component', template: '<ul> <li *ngFor="let res in results"> {{res}} </li></ul>' }) export class MyComponent { results: {}; constructor(private http: Http) { } app_func(){ this.http.get('http://someurl/id/test.json').subscribe( res => { this.results = res.json(); }) } ngOnInit(): void { this.app_func(); } And django template {% block bundles %} {% render_bundle 'main' %} {% endblock bundles %} {% block breadcrumbs %} {{ block.super }} {% breadcrumb test.name 'detail' test.id %} {% endblock breadcrumbs %} {% block content %} <div class="row"> <div class="col-md-12 col-md-offset-0"> <div class="test" id="results"> <my-component>Loading...<my-component> </div> </div> </div> {% endblock content %} I am getting the angular templates when i am using the static url (i.e exact url) in angular component. But i need to pass the {{test.id}} (which is from django views) value to angular component and use this … -
Django REST Framework doesn't display value in PUT form
Yesterday I posted a question and found a solution to that problem. The solution however caused another issue. Please take a look at the question, so I don't have to duplicate the contents. In the Browsable API the value for 'class_name' is not displayed in the PUT form. The rendered HTML looks like this: <div class="form-group "> <label class="col-sm-2 control-label "> Class </label> <div class="col-sm-10"> <input name="class_name" class="form-control" type="text"> </div> </div> For the other fields it displays the value properly, for example: <div class="form-group "> <label class="col-sm-2 control-label "> Order </label> <div class="col-sm-10"> <input name="order" class="form-control" value="Artiodactyla" type="text"> </div> </div> I poked around the source code and found out that the form is rendered in the file renderers.py in the following order: In the class BrowsableAPIRenderer the method get_context creates the form and calls the method get_rendered_html_form. The method get_rendered_html_form calls the method render_form_for_serializer. The method render_form_for_serializer calls the method render of the class HTMLFormRenderer. But I still don't know where to interfere and what should I change. Also I tried to implement the method to_internal_value in the serializer, but this is only for the deserialization and has nothing to do with the form rendering. Does anyone has an idea … -
How to register DRF router url patterns in django 2
My DRF routers specify a namespace so that I can reverse my urls: urls.py: router = DefaultRouter() router.register('widget/', MyWidgetViewSet, base_name='widgets') urlpatterns =+ [ url(r'/path/to/API/', include(router.urls, namespace='widget-api'), ] Which, when upgrading to django 2, gives: django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. Django 2 now requires app_name if the namespace kwarg is specified when using include. What's the right way to specify app_name when the url patterns are constructed by a DRF url router? I don't think the documentation is up-to-date for django 2 on this subject. -
Django project, aggregate(Sum) adding too much
I have a django project using views, models and forms. In forms I have a field called 'closed_cnt' that is supposed to add up all closed things. That is supposed to match against 'opened_cnt' and it usually works fine. But the thing is this is documented on different occasions and over a period of time. F.ex. a month ago I put 110 as opened_cnt and 30 as closed_cnt Then today I accidentally closed 8 instead of 80, and when I go back to fix it, it complains that the sum is too much, so what I have to do is put the value as 0, save it, then open again and put the value as 80. The code example for the field in models.py @property def closed_cnt(self): finished = self.finished() total_closed = finished.aggregate(Sum(closed_cnt)) So what I need is to not read the number I am overwriting and only read the new number. Is it possible to achieve this? -
How can I display this nested json object neatly and structured for the results object in django?
Here is my view.py: def dublinbus(request): template = loader.get_template('park_at_dcu/dublinbus.html') busstop = request.GET.get('busstop', '') busstop_url = 'https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid='+busstop+'&format=json' bus_time_info = requests.get(busstop_url) return HttpResponse(template.render(bus_time_info.json(), request)) Here is the json data: {"errorcode":"0","errormessage":"","numberofresults":1,"stopid":"1644","timestamp":"05\/12\/2017 12:22:09","results":[{"arrivaldatetime":"05\/12\/2017 13:11:49","duetime":"49","departuredatetime":"05\/12\/2017 13:11:49","departureduetime":"49","scheduledarrivaldatetime":"05\/12\/2017 13:12:00","scheduleddeparturedatetime":"05\/12\/2017 13:12:00","destination":"Clontarf Road ","destinationlocalized":" ","origin":"DCU","originlocalized":"DCU","direction":"Inbound","operator":"bac","additionalinformation":"","lowfloorstatus":"no","route":"104","sourcetimestamp":"05\/12\/2017 12:15:24","monitored":"true"}]} -
Django obtain query when calling function
i search a method to obtain query set when i calling sql function in my django's view : def gestionpaquet(request): try: cars=Car.objects.using("default").all() c=connection.cursor() c.execute("BEGIN") c.callproc("p_web_get_trunk") results=c.fetchall() c.execute("COMMIT") c.close() trunk="" trunks=[] for item in results: data=item[0] trunks.append(data) html = render_to_string("py/myhtml.html", locals()) except Exception as e: logger.warning("Error:" + e.message) return HttpResponse(html) In my template i correctly see cars but trunks doesn't work because trunks is not a query set, how can i obtain a query set when i execute function? Thanks. -
Gunicorn Error: HTTP_HOST header: 'wordist.org' (Django Project)
I'm developing a system through the django framework with gunicorn and nginx. But lately I realized that my system may be being hacked, because, I do not know how, the host www.wordist.com is infiltrated in my project. I've never seen this host in my life, but a error tells me to insert it into my ALLOWED HOSTS, and what's crazier, if I enter this host www.wordist.com into my ALLOWED HOSTS, then when I type this link in the url browser, this domain points to my project and shows my system, as if this domain www.wordist.com were mine, but I never saw this domain in my entire life. I suspect it's a hack or something malicious. Someone could help me unravel this case, and fix it. Thanks. -
Two Django projects with same database - permission denied for relation django_migrations
I have two django projects that are not connected in any way, both on localhost. I want to have them both use the same database. I am trying to create migrations on the second project after the first one succeeded but, I am getting an exception: django.db.utils.ProgrammingError: permission denied for relation django_migrations My setup is as follows: //First project DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'srt_side_by_side', 'USER': 'srt_side_by_side_admin', 'PASSWORD': '******************', 'HOST': 'localhost', 'PORT': '', } } //Second project DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'srt_side_by_side', 'USER': 'srt_side_by_side_admin_2', 'PASSWORD': '**************', 'HOST': 'localhost', 'PORT': '', } } I have granted SUPERUSER privileges to both users. I have tried to set individual privileges while being connected as the corresponding user in the psql shell. GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public to srt_side_by_side_admin_2; GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public to srt_side_by_side_admin_2; GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public to srt_side_by_side_admin_2; The DB access privileges in the psql shell: =Tc/simeonparvanov simeonparvanov=CTc/simeonparvanov srt_side_by_side_admin=CTc/simeonparvanov srt_side_by_side_admin_2=CTc/simeonparvanov Any idea what am I doing wrong? -
Find all items that are selected in a series of select lists
I currently have a page in my application that contains a Django formset. Each form in said formset consists of a Select2 field, rendered using django-autocomplete-light. I am using jQuery to make the formset dynamic (i.e. you can add and delete forms). The problem I am currently trying to solve is that I want to capture the value of the all the selected options from all the forms in the formset when the select2:open event is called when you click on the Select2 field. I have been having trouble doing this, as everything I have tried only returns the value for the current field and not all of them. I.e. I have been trying things like this: $('.s2mutex.keychar').on('select2:open', function (e) { let values = $('s2mutex.keychar').find('option:selected').val(); }); How can I find the values of all the options that have been selected? Here is my template as it stands: {% extends 'pages/dashboard.html' %} {% load i18n crispy_forms_tags static widget_tweaks %} {% block content %} <div> <h1 class="text-center">Create cost group - Set Key characteristics and Value fields</h1> <div class="row"> <div class="col"></div> <div class="col-md-8 col-lg-8"> <h3>Name: {{ object.eventconfig.eventconfigstepinitial.name }}</h3> <form role="form" method="post"> {% csrf_token %} {{ form|crispy }} <div id="formset"> {{ keycharacteristicfield_inline.management_form }} {{ … -
Django - JQuery AJAX : How to filter "POST"-ed json on "GET"?
When passing a JSON to Django views, it's supposed to be using POST. Using GET will append a long URL that would throw a long URI error. I am trying to implement a filter on objects in JSON type of functionality using ajax. I have two filter options, by text and by dropdown, where the users can filter one or the other or both. To do this I pass these two data using GET. So essentially its: JSON : POST filter1 & filter2 : GET Script $('#select_type').on('change', function () { filterGeoJson(); filterSearch(); }); $(function() { $('#search').keyup(function() { filterGeoJson(); filterSearch(); }); }); function filterSearch(){ $.ajax({ type: "GET", //url: "/search/get_routes/", url: "/search/routes/bounds", data: { 'search_text' : $("#search").val(), 'filter_type' : $("#select_type option:selected").val() }, success: function(data){ var result = $('<div />').append(data).find('#list-group').html(); $('#list-group').html(result); }, dataType: 'html' }); } function filterGeoJson(){ $.ajax({ type: "POST", //url: "search/get_routes/", url: "/search/routes/bounds/", contentType: 'application/json; charset=utf-8', data: { 'routes_geojson' : JSON.stringify(geojsonFeature) }, success: function(data){ var result = $('<div />').append(data).find('#list-group').html(); $('#list-group').html(result); }, dataType: 'html' }); } The main problem is, where I can't keep the POST-ed json (ofcourse, since its POST) but its also unconventional to make a global variable in Python (not like in Java) so I can't keep it until … -
what is detail_route and list_route in django rest framework
what is detail_route and list_route in django rest framework. i am new to django and its tough to understand from drf docs http://www.django-rest-framework.org/api-guide/routers/ -
Neovim pylint & pylint-django
I'm using pylint along with w0rp's ale vim/neovim plugin. I use it for django development. But I'm unable to configure pylint-django plugin. Every single time it shows a model doesn't have objects member. Thanks in advance.