Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a schedule status update in python Django. Like Fb page's schedule update
I try to make a social networking site using python django. In which i want to built schedule status update functionality where user make a posting schedule of their status update and on their schedule time it need to be posted on their timeline.is it any batter way to implement it rather then using celery or another scheduling task module? and can we use celery for that? -
Django/Python Serializing valuequeryset with number of objects limits per call (external service)
I am relatively new to Django and Python and have a quick question on the best way of going about breaking up serialization on object limits as apposed to call limits. I will be making calls to an external web service that limits the number of objects per call in addition to calls/timeframe. Currently I am creating a dictionary from a valuequeryset and then serializing. I have the json producing correctly, but I am looking for the best way to build the json in chunks. The API I am hitting allows for single object calls, but also calls with up to 5 objects. For example, I have a queryset with 25 records, what would be the best way to iterate through the list and break it into 5 json payloads which I could then iterate through, build json and fire off. Using the 5 per call instead of the 1 per call will help with the calls per time frame. Any help would be appreciated and thanks in advance. -
In my Dockered Django application, my Celery task does not update the SQLite database (in other container). What should I do?
This is my docker-compose.yml. version: "3" services: nginx: image: nginx:latest container_name: nginx_airport ports: - "8080:8080" volumes: - ./:/app - ./docker_nginx:/etc/nginx/conf.d - ./timezone:/etc/timezone depends_on: - web rabbit: image: rabbitmq:latest environment: - RABBITMQ_DEFAULT_USER=admin - RABBITMQ_DEFAULT_PASS=asdasdasd ports: - "5672:5672" - "15672:15672" web: build: context: . dockerfile: Dockerfile command: /app/start_web.sh container_name: django_airport volumes: - ./:/app - ./timezone:/etc/timezone expose: - "8080" depends_on: - celerybeat celerybeat: build: context: . dockerfile: Dockerfile command: /app/start_celerybeat.sh volumes: - ./:/app - ./timezone:/etc/timezone depends_on: - celeryd celeryd: build: context: . dockerfile: Dockerfile command: /app/start_celeryd.sh volumes: - ./:/app - ./timezone:/etc/timezone depends_on: - rabbit Normally, I have a task that executed every minutes and it updates the database located in "web". Everything works fine in development environment. However, the "celerybeat" and "celeryd" don't update my database when ran via docker-compose? What went wrong? -
Multiple ForeignKey to the same parent table, but with a unique identifier
I have the following data structure: State has state_id and name. (Example: California) Area has state_id, area_id and name (Example: Area of San Francisco, which contains some villages and San Francisco) Town has town_id, area_id, state_id, and name. (Example: Town of San Francisco) Street has street_id, town_id, area_id, state_id and name. Note the following: state_id is not a real ID (like an auto increment int), but a fixed number for each state. area_id is neither an auto increment int, but a fixed number. This means that two different states (big enough to have several areas), will have states with the same ID. (The state of San Francisco will have San Francisco (area_id = 1) and the state NY will have NY (area_id = 1). town_id... you guessed it, same as state_id and area_id. Don't insist on why the data is structured that way, it goes beyond the scope of this question and beyond what I'm allowed to refactor. So don't waste time on suggesting me to change that. I already know it's wrong, but I'm not allowed to fix it. Full stop. This means that a town must contain both the area_id and the state_id for it to be identificable. … -
Django forms submit radio button value shows up as None
I have a django form like this: class HelpForm (forms.form): queue = forms.ChoiceField( widget=forms.Select(attrs={'class': 'form-control'}), label=_('What can we help you with today?'), required=True, choices=() ) The choices for this form are populated in the views like this: form = HelpForm(initial=initial_data) form.fields['queue'].choices = [(q.id, q.title) for q in Queue.objects.filter(allow_public_submission=True)] + \ [('', 'Other')] The default rendering of this form in the templates when called as {{form.queue}} is a drop down list. But I needed it as a radio button field, so I did this in my template for each drop down value: <input type="radio" name="help_form" id="order_issues" value="{{form.queue.field.choices.2.0}}"/> <label for="id_order_issues">{{form.queue.field.choices.2.1}}</label> Now, when I submit this form, the queue value shows up as None even though I have made a selection and because this is a mandatory field, the form submit fails. Of course the form has other fields and they work as expected. What am I doing wrong? Any help will be appreciated! -
Error installing anaconda in docker container
I am quite new to docker. I am trying to make docker container to deploy web application (made by Django) to cloud. However, when I try to build by following Dockerfile, I got the error Using Anaconda API: https://api.anaconda.org ResolvePackageNotFound: -python 3.5.3 3 FROM ubuntu:16.04 # package install & update RUN apt-get update && apt-get -y upgrade RUN apt-get -y install build-essential RUN apt-get -y install git vim curl wget RUN apt-get -y install python-dev \ libmysqlclient-dev FROM continuumio/anaconda3 ENTRYPOINT [ "/bin/bash", "-c" ] ADD env.yml /tmp/env.yml WORKDIR /tmp RUN [ "conda", "env", "create", "-f", "env.yml" ] #ADD . /code/ RUN [ "/bin/bash", "-c", "source activate BAUES" ] #RUN [ "/bin/bash", "-c", "python manage.py migrate" ] #RUN [ "/bin/bash", "-c", "python manage.py runserver" ] Does anyone know why I am getting this error? Thank you. -
Django strange NoReverseMatch
I haven't found a solution to this online yet. By all accounts this should be working, but I'm still getting this error. urls.py urlpatterns = [ ... url( regex=r'^create/$', view=views.CreateOrderView.as_view(), name='create' ), ...] views.py class UploadSampleSheetView(LoginRequiredMixin, FormView): def post(self, request): ... if form.is_valid(): ... return reverse("orders:create", kwargs={'sample_sheet':sample}) class CreateOrderView(LoginRequiredMixin, CreateView): def get(self, request): return render(request, 'pages/complete_order.html') The error message is Reverse for 'create' with arguments '()' and keyword arguments '{'sample_sheet': Sample: Sample object}' not found. 1 pattern(s) tried: ['orders/create/$'] But when I just go to that url (/orders/create/) the page is there... I've tried return reverse("orders:create", kwargs={'sample_sheet':sample}) return reverse("create", kwargs={'sample_sheet':sample}) return reverse(orders:create, kwargs={'sample_sheet':sample}) return reverse(CreateOrderView, kwargs={'sample_sheet':sample}) But none work. Other answers here haven't helped me so far, nor have the docs. What's going on? -
Django server on amazon not reachable
I have a django application running on my localserver and it's working good and I cloned the final version of my repo on my AWS Ubuntu Instance, and added the AWS Instance IP as a valid IP in my settings.py Also, I added the port 8000 y my security group configuration. But, at the moment to run it: # python3 manage.py runserver 0:8000 Performing system checks... System check identified no issues (0 silenced). But, at moment to test it in the browser, I get: This site can’t be reached [the IP] refused to connect. Also, I tried to configure IPTable sudo iptables -I INPUT -p tcp -s 0.0.0.0/0 --dport 8000 -j ACCEPT but, still now working. Am I doing something wrong? -
ChoiceFieldRenderer removed. What is the solution?
It seems very few people used it, but... I did. Here you can read: Some undocumented classes in django.forms.widgets are removed: SubWidget RendererMixin, ChoiceFieldRenderer, RadioFieldRenderer, CheckboxFieldRenderer ChoiceInput, RadioChoiceInput, CheckboxChoiceInput My source code is: from django.forms.widgets import ChoiceFieldRenderer, RadioChoiceInput, \ RendererMixin, Select class BootstrapRadioFieldRenderer(ChoiceFieldRenderer): outer_html = '<span {id_attr}>{content}</span>' inner_html = '<div class="radio">{choice_value}{sub_widgets}</div>' choice_input_class = RadioChoiceInput class BootstrapRadioSelect(RendererMixin, Select): renderer = BootstrapRadioFieldRenderer _empty_value = '' I really dont know how to convert this to make it work with 1.11 and later: they say: Use a custom widget template instead. Well. How? -
Installing mysql-python inside cygwin - mysql_config not found [Windows 7]
I'm trying to install mysql-python for use with Django, but receive the following error: File "setup_posix.py", line 25, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) EnvironmentError: mysql_config not found I've seen other questions say this is due to it not being in the path. My path looks like this: /cygdrive/c/Users/ddnm/Documents/skincare/skincare/bin:/home/ddnm/bin:/usr/local/bin:/home/ddnm/.local/bin:/usr/local/bin:/usr/bin:/cygdrive/c/Windows/system32:/cygdrive/c/Windows:/cygdrive/c/Windows/System32/Wbem:/cygdrive/c/Windows/System32/WindowsPowerShell/v1.0:/cygdrive/c/Program Files (x86)/NVIDIA Corporation/PhysX/Common:/cygdrive/c/Users/ddnm/.babun:/cygdrive/c/Python27:/cygdrive/c/Python27/Lib:/cygdrive/c/Python27/DLLs:/cygdrive/c/Python27/Lib/lib-tk:/cygdrive/c/Program Files/MySQL/MySQL Server 5.7/bin In particular, I believe the problem is that mysql_config for Windows is a perl script, so the following is confusing cygwin: master » which mysql_config mysql_config not found master » which mysql_config.pl /cygdrive/c/Program Files/MySQL/MySQL Server 5.7/bin/mysql_config.pl Any suggestions/thoughts? Thanks -
Python Django Jinja2: How to use the range value within the for-loop statement as the index of a list?
I trying to display the items within a list. This is my code: #Django view.py file def display(request): listone = ['duck', 'chicken', 'cat', 'dog'] lents = len(list_one) listtwo = ['4 dollars', '3 dollars', '2 dollars', '1 dollars'] return render(request, 'display.html', {'itemone' : listone, 'itemtwo' : listtwo, 'lents' : lents}) This is the display.html file that display the list: <table> <tr> <th>Pet</th> <th>Price</th> </tr> {% for numbers in lents %} <tr> <td>{{ itemone.numbers }}</td> <td>{{ itemtwo.numbers }}</td> </tr> {% endfor %} </table> but with no luck it won't show the result according to the index 'numbers' which suppose to be from '0' to '3' the 'td' tags remaining empty. -
Annotating Django query sets through reverse foreign keys
Given a simple set of models as follows: class A(models.Model): pass class B(models.Model): parent = models.ForeignKey(A, related_name='b_set') class C(models.Model): parent = models.ForeignKey(B, related_name='c_set') I am looking to create a query set of the A model with two annotations. One annotation should be the number of B rows that have the A row in question as their parent. The other annotation should denote the number of B rows, again with the A object in question as parent, which have at least n objects of type C in their c_set. As an example, consider the following database and n = 3: Table A id 0 1 Table B id parent 0 0 1 0 Table C id parent 0 0 1 0 2 1 3 1 4 1 I'd like to be able to get a result of the form [(0, 2, 1), (1, 0, 0)] as the A object with id 0 has two B objects of which one has at least three related C objects. The A object with id 1 has no B objects and therefore also no B objects with at least three C rows. The first annotation is trivial: A.objects.annotate(annotation_1=Count('b_set')) What I am trying to design now … -
Django Model many to many self referenced with extra attributes
How can I create models in Django like this. t1 (id) t12 (id_1, id_2, status) t2 (id) -
django geoposition map doesn't appear in admin
I'm using django-geoadmin in a project and added it to my admin. When I access it, it shows the lat field, long, but not the google map. There are no errors in the browser console. I have the application configured correctly in settings.py: INSTALLED_APPS and GEOPOSITION_GOOGLE_MAPS_API_KEY. What can cause this? -
TemplateDoesNotExist at / in Django/Python Application
I am trying to run a Django Application with PyCharm and getting this error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.7.1 Python Version: 2.7.14 Installed Applications: ('django_admin_bootstrapped', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'compressor', 'menu', 'django_extensions', 'estabelecimento', 'bootstrap3', 'django_autocomplete', 'easy_select2', 'daterange_filter', 'qrcode') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Template Loader Error: Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: Using loader django.template.loaders.app_directories.Loader: C:\Users\Marcos\PycharmProjects\japedi\django_admin_bootstrapped\templates\index.html (File does not exist) C:\Python27\lib\site-packages\django\contrib\admin\templates\index.html (File does not exist) C:\Python27\lib\site-packages\django\contrib\auth\templates\index.html (File does not exist) C:\Python27\lib\site-packages\rest_framework\templates\index.html (File does not exist) C:\Python27\lib\site-packages\compressor\templates\index.html (File does not exist) C:\Python27\lib\site-packages\django_extensions\templates\index.html (File does not exist) C:\Users\Marcos\PycharmProjects\japedi\bootstrap3\templates\index.html (File does not exist) C:\Users\Marcos\PycharmProjects\japedi\daterange_filter\templates\index.html (File does not exist) C:\Users\Marcos\PycharmProjects\japedi\qrcode\templates\index.html (File does not exist) Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response 137. response = response.render() File "C:\Python27\lib\site-packages\django\template\response.py" in render 103. self.content = self.rendered_content File "C:\Python27\lib\site-packages\django\template\response.py" in rendered_content 78. template = self.resolve_template(self.template_name) File "C:\Python27\lib\site-packages\django\template\response.py" in resolve_template 54. return loader.select_template(template) File "C:\Python27\lib\site-packages\django\template\loader.py" in select_template 194. raise TemplateDoesNotExist(', '.join(not_found)) Exception Type: TemplateDoesNotExist at / Exception Value: index.html There are some directorys called templates inside the project. For every specific application there is one folder templates inside them. Anybody could help me with this? There is a version in a production environment with … -
When is template_name required in a ListView
I defined a Horario class in my models and I have a horario_list.html in my templates directory. If I define this class, everything works fine: class HorariosView(generic.ListView): model = Horario def get_queryset(self): return Horario.objects.all() However, if I change the return type by a list, like this class HorariosView(generic.ListView): model = Horario def get_queryset(self): return list(Horario.objects.all()) I get an exception TemplateDoesNotExist. Now, if I add a template_name property in my class, everything works again: class HorariosView(generic.ListView): model = Horario template_name = 'horario_list.html' def get_queryset(self): return list(Horario.objects.all()) When and why is template_name required? -
Manual activation of new user accounts in Django
I created a working "Log in with facebook" setup with django-allauth. However, I want those new user accounts that allauth creates to not be activated automatically. Basically I want to activate all new accounts from the Django admin pages. What would be a best practice solution to this? Thanks -
How can I consume real-time data from alphavantage API in python?
I try to use alphavantage API with my Django project. At the moment I am going to parse the JSON data in this way: from alpha_vantage.timeseries import TimeSeries def AlphaVantage(symbol): ts = TimeSeries(key='mykey') data = ts.get_intraday(symbol, interval='1min') print(str(data)) AlphaVantage('MSFT') In response I get data in this form: { "Meta Data": { "1. Information": "Intraday (1min) prices and volumes", "2. Symbol": "MSFT", "3. Last Refreshed": "2017-09-29 16:00:00", "4. Interval": "1min", "5. Output Size": "Compact", "6. Time Zone": "US/Eastern" }, "Time Series (1min)": { "2017-09-29 16:00:00": { "1. open": "74.4550", "2. high": "74.5041", "3. low": "74.4300", "4. close": "74.4900", "5. volume": "4761846" }, "2017-09-29 15:59:00": { "1. open": "74.4944", "2. high": "74.5000", "3. low": "74.4500", "4. close": "74.4550", "5. volume": "217391" }, "2017-09-29 15:58:00": { "1. open": "74.4400", "2. high": "74.5000", "3. low": "74.4400", "4. close": "74.4900", "5. volume": "157833" } ... However I would like to get only the most current data, in this case: "2017-09-29 16:00:00": { "1. open": "74.4550", "2. high": "74.5041", "3. low": "74.4300", "4. close": "74.4900", "5. volume": "4761846" } Any ideas how can I solve it? -
Django Rest DRF : getting count of objects for reverse relation
Let's say I have two models. Model class Item(models.Model): name = models.CharField(max_length=32) # other fields class ItemRelation(models.Model): item = models.ForeignKey(Item, related_name='relations_item') user = models.ForeignKey(User, related_name='relations_user') has_viewed = models.BooleanField(default=False) has_loved = models.BooleanFields(default=False) Now, what I want to do is I want to get the view_count and love_count for all items using django rest api. views.py class ItemView(ListAPIView): queryset = Items.objects.all().prefetch_related(Prefetch('relations_item', queryset=ItemRelation.objects.filter(Q(has_viewed=True) | Q(has_loved=True)) ) serializer_class = ItemSerializer Well, this was the plan but I have absolutely no idea how to get the view_count and love_count for each item in the list-api-view. I tried quite a few things on my serializer but I don't think it's going to work. I can however use SerializerMethod() to do the work, but that would go through the DB N+1 number of times. I have read through the docs along with a few other blogs for prefetch_related and I was able to do things easily until this count problem showed up. Just a sample from my serializer. class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ['name', 'relations_item'] -
python for loop output as list
I need to get some calculations for a range of elements at an array. So, at my views.py my code is: (...) for f in enumerate(array) calc1 = value_x calc2 = value y (...) and, when I print calc1, for example, my output returns 1 1 1 1 1 0.98 1 1 1 1 1 1 and, my output has to be like this ['1', '1', '1', '1', '1', '0.98', '1', '1', '1', '1', '1', '1'] I've already tried to do something like testLi = [] for f in enumerate(array): testLi.append(str(TPR_class)) print 'testLI {}'.format(testLi) but it gives me testLI ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'] testLI ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'] testLI ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'] testLI ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'] testLI ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'] testLI ['0.98', '0.98', '0.98', '0.98', '0.98', '0.98', '0.98', '0.98', '0.98', '0.98', '0.98', '0.98'] testLI ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'] testLI ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', … -
Django migrations failing with fresh database
wondering if anyone else is experiencing frustrating behavior with Django migrations. I have looked at several related posts on SO but have not found anything addressing this specifically. This keeps happening to me, and it MUST be a common scenario, so what am I missing? My scenario: List item I've built a Django application, iterating using sqlite on my local machine I now want to deploy to a production Postgresql db (AWS or elsewhere) I set up my new database, add it to my settings, and run python manage.py makemigrations I get a SQL error telling me that one of my model tables doesn't exist. Duh! That's why I'm running makemigrations. I end up having to hand-make tables, do weird things like python manage.py migrate <app_name> --fake which creates further issues with packages like simple_history I'm sure there must be an obvious answer -- what should I do to set up database schema on a brand new, clean database? -
Django ORM query, left join with where
I need to translate one query. Models class Publication_dependecy(models.Model): def __str__(self): return(str(self.id)) class Publication(models.Model): def __str__(self): return(self.name) name = models.TextField() class Publication_relationship(models.Model): def __str__(self): return(self.publication_from + '#' + self,publication + '#' + self.publication_dependecy_id) from_publication = models.ForeignKey(Publication, related_name='from_publication', on_delete=models.CASCADE) to_publication = models.ForeignKey(Publication, related_name='to_publication', on_delete=models.CASCADE) publication_dependecy = models.ForeignKey(Publication_dependecy, on_delete=models.CASCADE) SQL query: select Publication.id from Publication left join Publication_relationship on Publication.id = Publication_relationship where publication_dependecy is NULL or Publication_dependecy = 1 I need to retrive all publications that are not in Publication_relationship or his publication_dependecy is 1. In other words publication_dependency is 1 or NULL -
How to change Django paths/project/app
After going through How to change the name of a Django app? I am still having issues with my django setup The last time my django project 'ran' my setup was like this /resume ~/repos/resume /resume /apps /static /templates __init__.py settings.py urls.py wsgi.py ... manage.py requirements.txt ... The project name was resume and was in /repos/resume I changed the project name to portfolio and the directory to /repos/portfolio so that it becomes /portfolio ~/repos/portfolio /resume /apps /static /templates __init__.py settings.py urls.py wsgi.py ... manage.py requirements.txt ... I renamed them using pycharm's rename feature. I believe the references and such are updated correctly. Now when I am running python manage.py migrate (portfolio) nono@nono:~/repos/portfolio$ python manage.py migrate Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/nono/.virtualenvs/portfolio/src/django/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/home/nono/.virtualenvs/portfolio/src/django/django/core/management/__init__.py", line 300, in execute settings.INSTALLED_APPS File "/home/nono/.virtualenvs/portfolio/src/django/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/nono/.virtualenvs/portfolio/src/django/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/home/nono/.virtualenvs/portfolio/src/django/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/nono/.virtualenvs/portfolio/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", … -
Sending uploaded file to another pc over network
i am new to Django and just discover how to select and upload images using "https://github.com/axelpale/minimal-django-file-upload-example". now i want to again select a image from a uploaded files and send that select image to another computer over network. i want all this to be done in python and Django. search a lot but did not find any thing useful -
Django ImageKits "ImageSpecField" with values_list()
Im using Django ImageKit to generate thumbnails. I would like to get a "preview" Image from the existing ImageField. ImageKit provides a ImageSpecField model field but I have trouble using it in combination with values_list(). Since the ImageSpecField isn't a real database field ("ImageSpecFields, on the other hand, are virtual—they add no fields to your database and don't require a database. "), it can't be called through values_list(). Anybody an idea how to get the value of the ImageSpecField into the values_list? How does the ImageSpecFields exactly work? Is an Image generated each time the model gets called? I'm curios for efficiency reasons. What I tried? In the current state I would add a URLField into the model and write a function to save the output of self.thumbnail.url into the URLField but this doesn't seem very practical...