Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to install koalixcrm docker on synology DS918+, How to run docker compose on synology
I purchased a Synology DS918+ because I would like to install and run the docker file of koalixcrm https://github.com/scaphilo/koalixcrm. (This is a django based crm which requires postgresql docker as well Through the GUI i can only upload a docker file and install it but I need to run docker compose to set up the full application with the database. Does anyone known how to do this on the Synology? Thanks a lot for your help. -
Deploy readthedocs on production (nginx + gunicorn)
I am trying to deploy to a production server the project Read The Docs (http://docs.readthedocs.io/en/latest/install.html) for internal use at the company I work. I followed the install steps at the above url, it worked when I run with 'python manage.py 0.0.0.0:8000', but when I tried to deploy with Nginx + Gunicorn + Supervisord, the builds doesn't start, it keep showing 'Triggered version latest (html)' On the serve I got the error below, but I have no idea what I did wrong. Is the Read The Docs able to run with Nginx + Gunicorn + Supervisord? Do I have to install or configure celery? Thanks in advance! [09/Feb/2018 15:29:59] "GET /api/v2/project/2/ HTTP/1.1" 403 39 [09/Feb/2018 15:29:59] readthedocs.projects.tasks:159[15266]: ERROR An unhandled exception was raised during build setup Traceback (most recent call last): File "/webapps/readthedocs/src/readthedocs/projects/tasks.py", line 144, in run self.project = self.get_project(pk) File "/webapps/readthedocs/src/readthedocs/projects/tasks.py", line 299, in get_project project_data = api_v2.project(project_pk).get() File "/webapps/readthedocs/rtd_env/local/lib/python2.7/site-packages/slumber/__init__.py", line 155, in get resp = self._request("GET", params=kwargs) File "/webapps/readthedocs/rtd_env/local/lib/python2.7/site-packages/slumber/__init__.py", line 101, in _request raise exception_class("Client Error %s: %s" % (resp.status_code, url), response=resp, content=resp.content) HttpClientError: Client Error 403: http://localhost:8000/api/v2/project/2/ [09/Feb/2018 15:29:59] celery.app.trace:248[15266]: ERROR Task readthedocs.projects.tasks.update_docs[1cf185cd-57dd-478b-8689-bb795f26543c] raised unexpected: AttributeError("'UpdateDocsTask' object has no attribute 'setup_env'",) Traceback (most recent call last): File "/webapps/readthedocs/rtd_env/local/lib/python2.7/site-packages/celery/app/trace.py", … -
Django Celery Timezone setting not working
I have the following settings in my settings.py: TIME_ZONE = 'America/New_York' CELERY_TIMEZONE = 'America/New_York' USE_TZ = True But my tasks seem to be running in London time: 'add-every-minute': { 'task': 'api.tasks.add', 'schedule': crontab(minute='*/1', hour='8-17', day_of_week='1-5'), }, I tried following the steps here http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html to reset the time zone but I get this error instead: Model class djcelery.models.TaskMeta doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I'm using: python==3.6.2 Django==2.0.1 django-celery==3.2.2 sqlite3 -
Adding to cart quantity Django
I am trying to update the quantity on my cart but it doesn't actually update the quantity. My cart is model based but I think the problem line is here: product_obj['quantity'] += 1 I get an error: 'Product' object is not subscriptable My views.py def cart_update(request): product_id = request.POST.get('product_id') if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("Show message to user, product is gone?") return redirect("cart:home") cart_obj, new_obj = Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.add(product_obj) product_obj['quantity'] += 1 return redirect("cart:home") -
Preserve local time zone in serializer
I have a Django Rest Framework Serializer: class LocalTZDateTimeField(serializers.DateTimeField): def __init__(self, *args, **kwargs): local_timezone = pytz.timezone(getattr(settings, 'LOCAL_TIMEZONE', None)) kwargs['default_timezone'] = local_timezone super(LocalTZDateTimeField, self).__init__(*args, **kwargs)**strong text** which displays dates like this: "create_dt": "2016-01-04T09:06:17.344952-05:00" # Eastern time, as desired I don't want to show the fractional seconds, so the docs suggest specify a datetime format, which I did: 'DATETIME_FORMAT': "%Y-%m-%dT%H:%M:%S%Z%z", which mostly works, except now the dates are converted to UTC. "create_dt": "2016-01-04T14:06:17UTC+0000", I can't find anything that will allow me to show them in Eastern. (open to a better solution to supressing the fractional seconds, if I'm off the mark) -
Pull url from string
I have the string below I'm trying to pull the url out of out with python django. Thoughts on how I can get to it? I've tried treating it like a list but didn't have any luck. [(u'https://api.twilio.com/2010-04-01/Accounts/ACae738c5e6aaf12ffa887440a3143e55b/Messages/MM673cd77ab21b37ae435c1d1d5e767366/Media/ME33be4a0ae88358aaef2aa0ea25f31339', u'image/jpeg')] -
Django UpdateView with multiple models and multiple forms don't work
I am working with two different forms that loads info from two different models. One form is disabled to edit and the second form is enabled. Everything is right until I use UpdateView, when I try to make changes on the enable to edit form nothing happens. I am new in Django and found the code on a tutorial and adapted it to my project. Why UpdateView is not saving changes? models.py: class Sitioproyecto(models.Model): . . def __str__(self): return self.nombre_del_sitio class Sitiocontratado(models.Model): sitioproyecto = models.ForeignKey(Sitioproyecto, on_delete=models.CASCADE) . . def __str__(self): return self.sitioproyecto.nombre_del_sitio forms.py: class SitioContratadoForm(forms.ModelForm): class Meta: model = Sitiocontratado exclude = ['slug',] widgets = { 'fecha_de_contratacion' : forms.DateInput(attrs={ 'type' : 'date', 'class' : "form-control pull-right", 'id' : "fechadecon", }), 'sitioproyecto' : forms.Select(attrs={ 'type' : 'text', 'class' : "form-control", 'id' : 'nombresitio', }), . . } views.py: class CrearSitiosContratadosView(CreateView): model = Sitiocontratado template_name = 'sitios/contratados/editar_contratado.html' form_class = SitioContratadoForm success_url = reverse_lazy('pagina:tabla_contratados') class UpdateSitiosContratadosView(UpdateView): model = Sitiocontratado second_model = Sitioproyecto template_name = 'sitios/contratados/editar_contratado.html' form_class = SitioContratadoForm second_form_class = SitioProyectoForm success_url = reverse_lazy('pagina:tabla_contratados') def get_context_data(self, **kwargs): context = super(UpdateSitiosContratadosView, self).get_context_data(**kwargs) pk = self.kwargs.get('pk', 0) sitiocontratado = self.model.objects.get(id=pk) sitioproyecto = self.second_model.objects.get(id=sitiocontratado.sitioproyecto_id) if 'form' not in context: context['form'] = self.form_class() if 'form2' not in … -
How to serve static media with Daphne 2.0 on django
I'm new on daphne and I would like to know how to deploy a django app running on daphne, on ubuntu server. I already configured the app like the documentation said, and works fine, except that the static-files (js,css,imgs,etc) doesn't load. What I need to do? -
Can't get correct django form from template
please help to understand which one fomr model I should use on my case. I have the next form in HTML template : <div class="col-md-12"> <form id="developersform" action="#" method="post"> <select multiple="multiple" size="10" name="duallistbox_developers[]"> <option value="option1">Option 1</option> <option value="option2">Option 2</option> <option value="option3" selected="selected">Option 3</option> <option value="option4">Option 4</option> <option value="option5">Option 5</option> <option value="option6" selected="selected">Option 6</option> <option value="option7">Option 7</option> <option value="option8">Option 8</option> <option value="option9">Option 9</option> <option value="option0">Option 10</option> </select> <button type="submit" class="btn btn-default btn-block">Submit data</button> </form> </div> It's looks like View is not working due form issue: if request.user.is_authenticated: if request.method == 'POST': form = ManagmentUsersForm(request.POST) if form.is_valid(): picked = form.cleaned_data.get('duallistbox_guests') print(picked) else: form = ManagmentUsersForm() print(form.errors) How I should specify form on Django? Could someone help with example Thanks -
django migrating from sqlite3 to oracle causes ora-2000 error
I hava a Django app on a windows server 2012 which was set up with sqlite3 as the db, but it's going to production so I'm migrating the tables to oracle 12c on the server, i don't care about the data just the tables so when I run python manage.py migrate I get ORA-2000 Error: missing ALWAYS keyword I'm new to django and websites in general, what am i missing? -
can't connect django 1.10 to mysql 5.7, mysqlclient installed but still get ImportError: No module named 'MySQLdb'
I created a virtual environment with python 3.5 then used pip to install mysqlclient. When I activate the venv and go into the python shell I can type import MySQLdb and then proceed to query my db without any trouble. However, in django 1.10.5 when I use this virtual environment I get ImportError: No module named 'MySQLdb' as soon as I start the local/dev server. For what it's worth, I also tried this process outside of a virtual environment but no success. I'm on windows and Pycharm and created the venv in CMD with administrator privileges. I know there are similar questions on SO but nothing is on point here. Thanks for whatever help you can give! My settings are: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_db_name', 'USER': 'my_user_name', 'PASSWORD': 'my_password', 'HOST': '127.0.0.1', 'PORT': '3306' } } -
Using Django to create sessions and buttons connecting Products to a shopping cart through templates and views.py
Sorry for the length (Thought the info was relevant), and thank you for helping understand how this works. I'm trying to use sessions and Django templates to add items to shopping cart. I'm fairly new to learning Django and have painstakingly read through a bunch of documentation and Stack Overflow problems that were similar. My data is saved to MySQL database(subject to change) like this: sql_entry = { 'model': 'App.Product', 'pk': 1, # unique for each item 'fields': { 'Name': 'name', 'Price': 1.0, 'Quantity': 1 } and my Model: class Product(models.Model): Name = models.CharField(max_length=200, default='') Price = models.FloatField() Quantity = models.IntegerField() def __str__(self): return self.Name class Meta: ordering = ['Name'] Because the actual products will change daily, I want to avoid hardcoding categories, and thought it would be better to only have data pertaining to what products are available. So I use Django's template to create a basic table view of each product with a button that would add it to the cart. I want to avoid any type of login for now. I read that sessions was the best way for unique customers to add items to the cart and save there data to my database. I believe my … -
why doesn't django update form repopulate my fields with existing data
This is the template that should update existing model. I have looked through multiple tutorials but I still don't have a clue why my form's fields aren't prepopulated. Does anybody have any idea what's wrong? My form: class UpdateSiteForm(forms.ModelForm): class Meta: model = Site fields = ('name', 'description', 'URL',) my model: class Site(models.Model): name = models.CharField(max_length=255,unique=True) description = models.TextField(default='') URL = models.URLField(default=None) owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default=None) my template: {% extends 'base.html' %} {% block content %} <div class="updatesite"> <h2>{{site.name}} Update-page</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Update</button> </form> </div> {% endblock %} my views.py def updatesite(request,id): site = get_object_or_404(Site, id=id) dev = request.user if request.method == 'POST': form = UpdateSiteForm(request.POST,instance=site,initial=site) if form.is_valid(): form.save() return redirect('userhome') else: form = UpdateSiteForm() return render(request,'updatesite.html',{'site':site, 'form': form}) -
Set Environment Variables for Django on Dreamhost and Passenger WSGI
I'm trying to set an environment variable for Django that will not be in the source, in this case an email password. This is the example I'm trying to emulate: server: /etc/systemd/system/gunicorn-superlists-staging.ottg.eu.service [Service] User=elspeth Environment=EMAIL_PASSWORD=yoursekritpasswordhere WorkingDirectory=/home/elspeth/sites/superlists-staging.ottg.eu/source The example uses nginx and gunicorn, but I'm attempting a setup with Dreamhost, Linux and Passenger wsgi. Here is my file structure: . |-- \ ~ |-- __pycache__ |-- database |-- etc |-- passenger_wsgi.log |-- passenger_wsgi.py |-- passenger_wsgi.pyc |-- public |-- source |-- static |-- superlists |-- testGoat |-- tmp `-- virtualenv superlists is where the project is located. So, how should I go about setting the Environment Variables in this case? -
Ammending Django Views/Models for Cart Quantity
I have a Django cart project which adds and removes products from the cart. I can't seem to workout how I can add a quantity amount to the cart. I know I will need to add a quantity field to the model. But where do I change the logic - on the actual model or the view? Models.py (including manager) from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save, m2m_changed from catalogue.models import Product User = settings.AUTH_USER_MODEL # Create your models here. class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated() and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated(): user_obj = user return self.model.objects.create(user=user_obj) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True) products = models.ManyToManyField(Product, blank=True) # quantity = models.IntegerField() total = models.DecimalField(default=0.00, max_digits=10, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) def pre_save_cart_receiver(sender, instance, action, *args, **kwargs): if action == 'post_add' or action == 'post_remove' or action == 'post_clear': … -
Nginx can't download files bigger than a few MB's (403 forbidden)
Something really strange is happening. Whenever i try to download a file that is bigger than a few MB's, it returns a 403 forbidden message. This is my sites-enabled conf: server{ listen 80; server_name braduletfumat.go.ro; location = /favicon.ico {access_log off; log_not_found off;} location /static/{ root /var/www/BrdWeb/Bradulet/; } location / { include proxy_params; proxy_max_temp_file_size 0; proxy_pass http://unix:/var/www/BrdWeb/Bradulet/Bradulet.sock; } location /protected/{ internal; proxy_max_temp_file_size 0; alias /var/www/BrdWeb/Bradulet/; } } And the nginx conf: user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; client_max_body_size 4G; } I am using django and X-Accel-Redirect for serving the files. Before, it returned an … -
Getting all objects with equal M2M fields
I am looking for a way to filter for all objects of the same type that have the same querysets for a M2M field. class Comment(models.Model): user = models.ForeignKey(User, related_name='comment_user') content = models.CharField(max_length=5000, null=True) private_to = models.ManyToManyField(User, null=True, related_name='private_to') Given a comment object, I want to retrieve all other comments who have an equal M2M field (i.e. if the private_to field returns User 1 and User 2 for the comment, it will find all the other comments that contain exactly both of those users in the private_to field.) Is there a concise, built-in way to do this? -
XlsxWriter exported file sometimes can't be opened by Numbers
This is a server rendered file, so it's saved to a Django HttpResponse with {"in_memory": True} During QA testing, sometimes the file can't be opened by Numbers. It says "calendar.xlsx" can't be opened right now. The file format is invalid. Yet it opens in LibreOffice just fine. No one here uses Windows so I haven't tested Excel yet. What info can I gleam from the file that will shed more info on this? -
HOW to create a multi-step form using ModelForm is django
I am attempting to create a multistep modelform because I want to save the data. I am using the formtool called FormWizard, however I am having difficulty using it for a model form Instructions User clicks on create patient link User opens patient form User inserts patient data User submits form if form is invalid: redisplay form with error if form is valid: move to next form enter symptom data submit form if form is invalid: redisplay form with error if form is valid: move to next form enter disease data submit form if form is invalid: redisplay form with error if form is valid: User is redirected to general form that has patient + symptom + disease information. THIS is the view that will create the multi-step model form class ConsultationCreate(SessionWizardView): instance = None def get_form_instance(self, step): if self.instance is None: self.instance = Patient return self.instance template_ = 'data/multi_form.html' def done(self, form_list, **kwargs): self.instance.save() def process_form_data(form_list): form_data = [form.cleaned_data for form in form_list] logr.debug(form_data[0]['NIS']) logr.debug(form_data[1]['identity']) logr.debug(form_data[2]['identity']) return form_data This is the error it produces : ValidationError at /patient/create ['ManagementForm data is missing or has been tampered.'] This is the code ================================================================== urls.py from django.conf.urls import url from data.views import … -
Is there a way to run tests in Django without creating database?
I'm getting an error in a simple functional test that I suspect is related to creating a large database. The error is ConnectionRefusedError: [Errno 111] Connection refused It takes sometime until database is created and to test if the error is related to this, I would run the test without creating the test database. Is it possible to run tests with python manage.py test functional_test.py skipping the database creation? -
uploading csv to database fails on cells that are null
Django 2.0 PostgreSQL 10 It is crucial that my app allows users to upload data in bulk, for which they can upload a csv file. However for any field that is non-string, if a cell on the csv file is Null then it returns the following error: ["'' value has an invalid date format. It must be in YYYY-MM-DD format."] This exception was copied in the case of a empty cell under the Date column, however it's the same for int and float. The exception is straightforward. However according to the csv documentation, the value None is written as the empty string although this is stated under the csv.writer section and not under csv.reader. I'm having a hard time understanding why the ORM is not converting empty strings to None or Null values that the database does understand, and as stated in my models.py, it accepts. models.py: class Control(models.Model): date = models.DateField(default=date.today, null=True, blank=True) kilos = models.FloatField(null=True, blank=True) views.py: class ControlFileUpload(View): def get(self, request): return render(request, 'csv_upload.html') def post(self, request): file = request.FILES['csv_file'] _control_bulk_data_upload(file) #imported from utils.py return render(request, 'csv_upload_success.html') utils._control_bulk_data_upload: import csv, datetime from app.models import Control def _control_bulk_data_upload(csv_file): path = default_storage.save("{}_{}".format(datetime.utcnow(), csv_file.name), ContentFile(csv_file.read())) with open(path) as csvfile: reader … -
Python - Check if user is in team or not
I have a model that stores teams and members. I want to check if a requested user is in this team or not. How do i do that? Model class TeamPlayer(models.Model): team = models.ForeignKey(Team, related_name='players', on_delete=models.CASCADE) player = models.OneToOneField(User, related_name='player', on_delete=models.CASCADE) approved = models.BooleanField(default=False) Template {% if request.user in object.players.all %} <a href="{% url 'teams:leave' pk=object.id %}" class="btn btn-warning">Leave</a> {% else %} <a href="{% url 'teams:join' pk=object.id %}" class="btn btn-success">Join</a> {% endif %} View is just simple DetailView. -
Model forward declarations
I'm writing configuration dictionaries into my models. I need to access the forwarded declaration of model declared below the model im configuring right now. For example class FirstModel(models.Model): TYPE_MODEL = { 'type1': SecondModel, 'type2': ThirdModel } some_field = models.CharField( choices=( ('type1', 'type 1 display'), ('type2', 'type 2 display') ) ) def do_some_with_config(self): model = self.TYPE_MODEL.get(self.some_field) ... do something with model ... class SecondModel(models.Model): ... its own fields ... class ThirdModel(models.Model): ... its own fields ... Is here any better approach to do this than moving the FirstModel below the ThirdModel or is it generally a good idea to have these dicts with configuration in the model? -
when i removed the last line from code the error is gone but it doesn't provide required output Django 1.8
from django.contrib import admin Register your models here. from .models import SignUp class SignUpAdmin(admin.ModelAdmin): list_display = ["str","timestamp","updated"] class Meta: model = SignUp admin.site.register(SignUp, SignUpAdmin) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: : (admin.E108) The value of 'list_display[2]' refers to 'updated', which is not a callable, an attribute of 'SignUpAdmin', or an attribute or method on 'newsletter.SignUp' -
django dynamic formset how to find id of a dynamic created form
I use django dynamic formset javascript, I want to do use ajax on each form. However I can't find a way to get the id of a newly created dynamic form. html {% for forms in formset %} {{ forms.id }} <tr class="dynamic"> <td style="width:100px">{{ forms.stock.errors }} {{ forms.stock}} </td> <td style="width:100px">{{ forms.inventory.errors }} {{ forms.inventory}} </td> my ajax $(document).ready(function(){ {% for forms in formset %} $("#{{forms.stock.auto_id}}").change( function(){ var symbol = $("#{{forms.stock.auto_id}} option:selected").text(); $.ajax({ url: "{% url 'inventory:get_position' ptinventory_obj.id date %}", type: "GET", data: { 'product': product }, datatype: 'json', success: function(data) { $("#{{forms.inventory.auto_id}}").html(data.price); }}); }); {% endfor %} }) forms.inventory.auto_id stays the same for all new forms so any changes on stock.nothing is shown. I looked at the source from chrome and can see the ide changes for the input field for each form...but the {{forms.inventory.auto_id}} is clearly not the right tag.Please help...