Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to insert data instance from view in django?
I have a problem to insert instance data in django, this is my model class DipPegawai(models.Model): PegID = models.AutoField(primary_key=True) PegNamaLengkap = models.CharField(max_length=100, blank=True, null=True) PegUser = models.OneToOneField(User, null=True, blank=True, unique=True) class DipHonorKegiatanPeg(models.Model): KegID = models.AutoField(primary_key=True) PegID = models.ForeignKey(DipPegawai) this is my view def tambah_klaimhonor(request): klaim = {} user = request.user.id honoruser = DipHonorKegiatanPeg(DipPegawai) if request.method == 'POST': form = KlaimHonorGuruKarForm(request.POST, instance=honoruser) if form.is_valid(): form.save() # form.save() return redirect('index_klaimhonor') klaim['form'] = KlaimHonorGuruKarForm() return redirect('index_klaimhonor') when i insert data, i get this error Traceback: 23. return view_func(request, *args, **kwargs) File "C:\Users\Lenovo\OneDrive\sisgaji\honorkegiatanpeg\views.py" in tambah_klaimhonor 120. form.save() File "C:\Users\Lenovo\hrd\lib\site-packages\django\forms\models.py" in save 451. self.instance.save() File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\base.py" in save 700. force_update=force_update, update_fields=update_fields) File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\base.py" in save_base 728. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\base.py" in _save_table 793. forced_update) File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\base.py" in _do_update 823. filtered = base_qs.filter(pk=pk_val) File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\query.py" in filter 790. return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\query.py" in _filter_or_exclude 808. clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\sql\query.py" in add_q 1243. clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\sql\query.py" in _add_q 1269. allow_joins=allow_joins, split_subq=split_subq, File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\sql\query.py" in build_filter 1203. condition = self.build_lookup(lookups, col, value) File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\sql\query.py" in build_lookup 1099. return final_lookup(lhs, rhs) File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\lookups.py" in __init__ 19. self.rhs = self.get_prep_lookup() File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\lookups.py" in get_prep_lookup 57. return self.lhs.output_field.get_prep_lookup(self.lookup_name, self.rhs) … -
dynamic form template based on the field type
I am doing the django project right now. I love the principle of DRY. I have a form which can be applied to all other pages which needs it. I mean a generic form based from django docs. But in the form, there can be select type, file upload, checkbox, radio etc which I dont like the design of native html. I want to leverage the design of material with some customization. I want it be done in template not from the forms.py. How can I do it? Below is my form and my form has checkbox, file upload and multiple select which I need to customize. In a nutshell, my question is how do I make my generic form designer friendly? form.html <form class="form" role="form" action="" method="post" enctype='multipart/form-data'> {% csrf_token %} {% for field in form %} {% if field.errors %} <div class="form-group label-floating has-error"> <label class="control-label" for="id_{{ field.name }}">{{ field.label }}</label> <div class="col-sm-10"> {{ field|add_css:'form-control' }} <span class="help-block"> {% for error in field.errors %}{{ error }}{% endfor %} </span> </div> </div> {% else %} <div class="form-group label-floating"> <label class="control-label" for="id_{{ field.name }}">{{ field.label }}</label> {{ field|add_css:'form-control' }} {% if field.help_text %} <p class="help-block"><small>{{ field.help_text }}</small></p> {% endif %} … -
Django Avoid Data Repetition
Here's my code, question = Question.objects.annotate(ans_count=Count('answer')).filter(ans_count=True).order_by('-answer').distinct() I'm using "sqlite3". .distinct() is not working since it's repeating the questions. This way if a question gets 2 answers suddenly it will appear twice in the feed. How can I restrict it from appearing multiple times in the feed? Thank You :) -
Django html template will not display database variables
I am new to django and am having trouble getting database items to display on my website using a html template. I have made sure that the queryset for the database exists and has items in it, and I can display text on the home page fine as long as the template does not have any variables. Currently my home page displays only the Title and the rest is blank. Python 3.5, django 1.11, sqlite3. models.py: from django.db import models from django.utils import timezone from django.contrib import admin class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() image = models.ImageField(upload_to= 'static/media/', default = 'static/media/Firefox_wallpaper.png') created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title views.py: from django.shortcuts import render from .models import Post from django.utils import timezone def post_list(request): posts=Post.objects.filter(published_date__lte=timezone.now()) .order_by('published_date') return render(request, 'main/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'main/post_detail.html', {'post': post}) base.html: {% load staticfiles %} <html> <head> <title>Title</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> </head> <body> <div class="page-header"> <h1><a href="/">Title</a></h1> </div> <div class="content container"> <div class="row"> <div class="col-md-8"> {% block content … -
apache(cpanel) + mod_wsgi + Python3 + Service Temporarily Unavailable
Goodnight everyone. I'm trying to do the deployment of an application developed with django in a VPS. This VPS has installed centos 6.8. Apache is configured through the cpanel. After installing python3 and wsgi proceeded to configure the icnlude of the virtual host, which was as follows: <ifmodule mod_wsgi.c> WSGIDaemonProcess pruebas.caso.org python-path=/home/admin/pruebas.org/envSpf/spf:/home/admin/pruebas.org/envSpf/lib/python3.5/site-packages/ WSGIProcessGroup pruebas.caso.org WSGIScriptAlias / /home/admin/pruebas.org/envSpf/spf/spf/wsgi.py </ifmodule> Alias /static "/home/admin/pruebas.or/envSpf/spf/static/" <Directory /home/admin/pruebas.or/envSpf/spf/static> Require all granted </Directory> Alias /media "/home/admin/pruebas.or/envSpf/spf/media/" <Directory /home/admin/pruebas.or/envSpf/spf/media> Require all granted </Directory> <Directory /home/admin/pruebas.or/envSpf/spf/spf> <Files wsgi.py> Require all granted </Files> </Directory> With this configuration at the moment the server gives me the following response in the browser request: Service Temporarily Unavailable The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later. Additionally, a 503 Service Temporarily Unavailable error was encountered while trying to use an ErrorDocument to handle the request. The VPS provider is not very helpful and the error log refers to another domain (?? !!!). I would appreciate any guidance that could help me resolve this inconvenience. -
Update first_date and last_date to counting customers per period
In my django project, it is possible to show every customer in the application with CustomerProfile.objects.all() and find the creation date of a specific customer with In [12]: cust = CustomerProfile.objects.get(pk=100) In [13]: cust.user.date_joined Out[13]: datetime.datetime(2017, 7, 28, 14, 43, 51, 925548) In [14]: cust Out[14]: <CustomerProfile: FistName LastName's customer profile> According to the creation date, I would like to make a listing of how many customers has been created per day, week, month or year. An example of the result could be ... week 28 : [ 09/07/2017 - 15/07/2017 ] - Count : 201 customers ... I probably need a range start_date and end_date where we will list that kind of information. start_date will be the date of the first customer created and the start_week created would be the week of this first_date. Obviously, the end_date is the date of the last customer created and last_week is the week of this end_date. For instance, if I select Per week in the drop-down menu and press Apply in the form, I want to send information to my model in such I could code what I explained. So far I know how to count the number of client in a … -
Django Rest Framework or JsonResponse
I want to make my current more interactive by having ajax that calls for json data, I haven't done anything yet except for research and studying. Here are some things I am not very clear. If JsonResponse and DRF can give the json data i need how is DRF different from JsonResponse ? -
Django, Querying the Database
Here's my model, class Question(models.Model): .... class Answer(models.Model): question = models.ForeignKey(Question) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) I wants to filter out the questions which received maximum answers in last 24 hours. How can I do that? Thank You :) -
bijectivity between the view and the model
I am a new programmer in Django/Python, and I need your help. Here what I got so far : views.py class StatisticsIndexView(StaffRestrictedMixin, TemplateView): model = Statistics() template_name = 'loanwolf/statistics/index.html' form_class = StatisticsBaseForm() def get_context_data(self, **kwargs): context = super(StatisticsIndexView, self).get_context_data(**kwargs) context.update({ 'applications_by_state': ApplicationsByState(), 'applications_calendar': ApplicationsCalendar(), 'new_customers_calendar': NewCustomersCalendar(), 'statistics': Statistics(), 'form': StatisticsBaseForm(), }) return context models.py class Statistics(TimeStampedModel): def nb_of_customers_per_period(self): return CustomerProfile.objects.filter(user__date_joined__range=["2017-09-03", "2017-09-09"]) From my view model, I know that <QueryDict: {u'from_regular_product': [u'1'], u'product_type': [u'regular'], u'period': [u'week'], u'from_special_product': [u''], u'apply': [u'Apply'], u'type_choice': [u'0'], u'debit_frequency': [u'1month']}> You have to know that u'period' has exactly for choices, i.e., day, week, month and year. In my django project, it is possible to show every customer in the application with CustomerProfile.objects.all() and find the creation date of a specific customer with In [12]: cust = CustomerProfile.objects.get(pk=100) In [13]: cust.user.date_joined Out[13]: datetime.datetime(2017, 7, 28, 14, 43, 51, 925548) In [14]: cust Out[14]: <CustomerProfile: FistName LastName's customer profile> Question: Here is my problem. I would like to consider the value of u'period' from self.request.GET inside my model. How to communicate the result from my view inside my model (clear??). The purpose is to tell how many customers has been created in the current period. In pseudocode, this gave … -
passing JavaScript variable to Django
How can I pass a js variable to Django? I have this simple code: $(".update_btn").click(function() { var row_id=$(this).attr("row_id") I want to pass row_id as index to a Django parameter called ticket_row, so that I could have ticket_row[row_id][1] I started to pass the first index with console.log("{{ ticket_row['" + row_id + "'] }}") but it's working correctly. So, I need some help here :) Any one has any suggestion / solution? Thanks! -
Why I'm unable to create core 'blog' in Solr 4.10.4?
I'm trying to integrate Apache Solr with my Django blog application. I'm using Apache Solr 4.10.4 downloaded from https://archive.apache.org/dist/lucene/solr/4.10.4/. I started Solr in terminal by typing java -jar start.jar in terminal as normal user. I tried create a new core with following parameters: name: blog instanceDir: blog dataDir: data config: solrconfig.xml schema: schema.xml But I'm getting error while creating core: Error CREATEing SolrCore 'blog': Unable to create core [blog] Caused by: null Also below error occures when initalization: SolrCore Initialization Failures blog: org.apache.solr.common.SolrException:org.apache.solr.common.SolrException Please check your logs for more information Directory structure in ~/Downloads/solr-4.10.4/example/solr/blog: pecan@tux ~/Downloads/solr-4.10.4/example/solr $ tree blog blog ├── conf │ ├── lang │ │ └── stopwords_en.txt │ ├── protwords.txt │ ├── schema.xml │ ├── solrconfig.xml │ ├── stopwords.txt │ └── synonyms.txt ├── data │ └── index │ ├── segments_1 │ ├── segments.gen │ └── write.lock ├── nfa_regexp_debug.log ├── nfa_regexp_dump.log └── nfa_regexp_run.log 4 directories, 12 files Could anybody tell me what I'm doing wrong? -
Django change background color using button
I want to change background color, where user button touch. Info with color should be stored at my DB. HTML: <div class={{colors}}> where class = "card card success/info/warning flex-item" Buttons: <a href="{% url 'board:success_button' %}"><button type="button" class="btn btn-outline-success">Done!</button></a> <a href="{% url 'board:warning_button' %}"><button type="button" class="btn btn-outline-warning">In progress...</button></a> <a href="{% url 'board:danger_button' %}"><button type="button" class="btn btn-outline-danger">Canceled</button></a> urls.py: url(r'^$', views.success_button, name='success_button'), url(r'^$', views.warning_button, name='warning_button'), url(r'^$', views.danger_button, name='danger_button'), views.py: def success_button(request): color = Card.objects.create(colors="card card success flex-item") color.save() def warning_button(request): color = Card.objects.create(colors="card card info flex-item") color.save() def danger_button(request): color = Card.objects.create(colors="card card warning flex-item") color.save() models.py: colors = models.CharField(max_length=200) Description. Card have bootstrap background color - > success, info and warning. User touch info button, then background ( class ) change to card info and it storing at DB. Thanks in advance! -
Django Restful API App
I made a new API app to serve all the API requests for my web app. So I want to first do something simple and return a DataFrame object in the form of JSON. I am also using the Django Rest Framework Library. My urls.py from django.conf.urls import url, include from rest_framework import routers from api import views router = routers.SimpleRouter() router.register(r'test', views.UserViewSet) urlpatterns = [ url(r'^', include(router.urls)) ] My views.py: class UserViewSet(APIView): renderer_classes = (JSONRenderer, ) def get(self): queryset = NAV.objects.filter(fund__account_class=0, transmission=3).values('valuation_period_end_date').annotate( total_nav=Sum(F('outstanding_shares_par') * F('nav'))).order_by('valuation_period_end_date') df = read_frame(queryset, coerce_float=True) df.loc[:, 'valuation_period_end_date'] = pd.to_datetime(df.valuation_period_end_date) df.loc[:, 'timestamp'] = df.valuation_period_end_date.astype(np.int64) // 10 ** 6 df.loc[:, 'total_nav'] = df.total_nav return JsonResponse(df) But I get the error AssertionError:base_nameargument not specified, and could not automatically determine the name from the viewset, as it does not have a.querysetattribute. I am new to Django Restful API Framework and was wondering if I am doing this right? -
TypeError: Error when calling the metaclass bases
TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution order (MRO) for bases StaffRestrictedMixin, StatisticsIndexView I have this type of error, but I can't fix it regardless the other similar questions. views.py class StatisticsIndexView(StaffRestrictedMixin, TemplateView): model = Statistics() template_name = 'loanwolf/statistics/index.html' form = StatisticsBaseForm() def get_context_data(self, **kwargs): context = super(StatisticsIndexView, self).get_context_data(**kwargs) context.update({ 'applications_by_state': ApplicationsByState(), 'applications_calendar': ApplicationsCalendar(), 'new_customers_calendar': NewCustomersCalendar(), 'statistics': Statistics(), 'form': StatisticsBaseForm(), }) return context class StatisticsSubmitView(StaffRestrictedMixin, StatisticsIndexView): model = Statistics() What do you suggest to fix that issue? -
Avoiding multiple AJAX calls on jquery sortable( )
I am new to JQuery. Basically I have a table which I can sort the rows. I want to save the new order in the backend, which I am able to do. However, I noticed that I am sending multiple Ajax calls depending on the number of times I sorted the table. The order is not saving properly in the backend. Here is my code. The variable order is where the new IDs are stored. I am sending it in my Django through the '/updateorder' route/ <script type="text/javascript"> $(document).ready(function(){ $("#sortable").sortable({ update: function (event, ui) { var order = $(this).sortable('toArray'); console.log(order); $(document).on("click", "button", function () { $.ajax({ data: {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value, 'order[]': order}, type: 'POST', url: '/updateorder' }) }); } }).disableSelection(); $('button').on('click', function () { var r = $("#sortable").sortable("toArray"); var a = $("#sortable").sortable("serialize", { attribute: "id" }); console.log(r); }); }); </script> How can I avoid sending multiple Ajax calls when I click on the button? Also, what is the correct way to redirect to a different page after the logic is executed? Thanks for reading! PS: I am using python/django in the backend -
Passing an image from view to template
Basically, my django app needs to create an image in a view, and pass that to a template. This is easy for a string, but I can't find a way to do it with an image. I have read many stack overflow threads but none quite like mine, which is surprising. I was trying variations of this as my view: views.py: def index(request): while (True): #video_capture = cv2.VideoCapture(0) #ret, frame = video_capture.read() img = "D:/Desktop/Tap/bsnsFaces.jpg" frame = cv2.imread(img) facesNumber ="Found {0} faces!".format(len(faces)) return render(request, 'result.html', {'p': facesNumber}, {'img': frame})` With the {'img':frame} part at the end not being anywhere close to right. I tried a few things that I found on SO but nothing worked so far. I know that the image is static but eventually I want this to be a frame captured from a webcam so I can't solve this by using models (or can I?). Thanks in advance for any advice! -
serializers validation method is not validating list of objects for the first time
models.py class Customer(models.Model): name = models.CharField(max_length=128) email = models.EmailField(null=True, blank=True) phone = models.CharField(max_length=128) serializers.py class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ("name", "email", "phone") extra_kwargs = { "email":{"required":True}, } def validate_email(self, email): qs = Customer.objects.filter(email__iexact=email) if qs.exists(): raise serializers.ValidationError("This email is already existed") return email def validate_phone(self, phone): qs = Customer.objects.filter(phone__iexact=phone) if qs.exists(): raise serializers.ValidationError("This Phone is already existed") return phone views.py class CustomerApi(SerializerMixin, APIView): ...... ......... def post(self, request): serializer = CustomerSerializer(data=request.data, many=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response( serializer.errors, status = status.HTTP_400_BAD_REQUEST ) json [ { "phone": "123", "name": "name1", "email": "123@ll.cc" }, { "phone": "123", "name": "nam32", "email": "123@ll.cc" } ] the above customer json list have two objects with same email and phone . But it is not validating the email and phone(validation methods are not working) when i create if for the first time. But once it get created, the second time when i try to create the customer with the same list, validation method is working as expected. i couldn't trace out the problem. -
Try to save data in form, but Django won't recognize User
I'm trying to save data input using a form, but I'm running into a problem where Django won't recognize the user. I always get this error message: "Cannot assign ">": "Post.user" must be a "User" instance." This is what I have so far in my models: from django.db import models from django.contrib.auth.models import User class Post(models.Model): post = models.CharField(max_length=500) user = models.ForeignKey(User) My forms: from django import forms from firstapp.models import Post class IndexForm(forms.ModelForm): post = forms.CharField() class Meta: model = Post fields = ('post',) And my views: from django.shortcuts import render, redirect from firstapp.forms import IndexForm from django.views.generic import TemplateView class HomePage(TemplateView): template_name = 'home/home.html' def get(self, request): form = IndexForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = IndexForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() text = form.cleaned_data['post'] form = IndexForm() return redirect('home:home') args = {'form': form, 'text': text} return render(request, self.template_name, args) Any idea what's going on? -
Unable to transfer Data from models to html using templates
View.py from django.shortcuts import render from django.http import HttpResponse from .models import Albums from django.template import loader def index(request): all_albums = Albums.objects.all(); template = loader.get_template('Ganaana/index.html'); context = { 'all_albums':all_albums, } return HttpResponse(template.render(context,request)) def define(request,Albums_id): return HttpResponse("<h1>Your Id is "+str(Albums_id)+"</h1>"); index.html <ul> <% for albums in all_albums %> <li><a href="/music/{{albums.id}}/">albums.artist</a></li> <% endfor %> </ul> I dont know what the error i used templates folder and put data in it i dont understand what the problem i import class correctly.. i dont understand? -
Django, show and hide details of items in a ListView with jQuery
I have a ListView in django which I'm trying to show/hide extra details for each item when a 'More info' button is pressed. The issue is with trying to get a unique identifier for each item in the django template that javascript can act on to hide/show a specific item details rather than all of them. The javascript bit definitely isn't right. <div class="quotes"> {% for quote in quotes_results %} <div> <h3>{{ quote.supplierName }}</h3> <div> </div> <a class="btn btn-cta-primary" href="{% url 'users:profile' price_id=quote.priceId %}">Proceed</a> <button class="btn btn-cta-secondary" id="button">More Info</button> </div> <div class="til" id="til{{ quote.priceId }}"> <p>test hide and show more details</p> </div> {% endfor %} </div> {% block inner_js %} <script type="text/javascript"> $(document).ready(function () { $('#button').click(function (priceId) { $('#till' + priceId).toggle() }) }) </script> {% endblock inner_js %} -
Model default values from another model
Is it possible to use default values stored in one model to populate the default values in another? My app has a form with approx 15 fields. Users often have to complete the form 20-30 times. About 2/3rds the data is identical each time, so what I'd like to do is prepopulate the form with default data so that the user only needs to edit 3-4 fields. The default values are different for each user so my thought is to capture the first form data in a 'defaults' table linked to the user, then use default to pre-populate the form every time thereafter. Is this a reasonable approach? Can it be done? Is there a better way? -
How to use a reg. form to pass a variable in the url and render results in django?
If I submit 'http://localhost:8000/item/2/' to the address bar, I get the desired result, which is a rendering of item_detail.html with its item variables filled. But when I try to pass the ‘2’ via a form, I only get the html without rendering (and instead displaying in the console upon a console.log. How can I use a form to get the initial result? And is there an easiest way to do this? I've added the code below... thanks. INDEX.HTML <form id="form"> Item Name:<br> <input id="entry" type="text"><br> <input type="submit" value="Submit"> </form> MAIN.JS var form=$("#form") $(document).on("submit", "#form", function (e) { e.preventDefault(); var term = $("#entry").val() var query="/item/"+term $.ajax({ type: 'GET', url: query, }).done(function(response) { console.log(response) }) }) URL.PY url(r'^item/(?P<id>\d+)/', views.item_detail, name='item_detail'), VIEWS.PY def item_detail(request, id): try: item = Item.objects.get(id=id) except Item.DoesNotExist: raise Http404("This item doesn't exist") return render(request, 'inventory/item_detail.html',{ 'item': item, }) MODELS.PY class Item(models.Model): title = models.CharField(max_length=200) description = models.TextField() amount = models.IntegerField() -
django display media files local server
I've been researching this for a while. I think there is a problem with my index.html file where i'd like to display the pic. There is user uploaded jpg files stored in: media\user\profile\id_1\pic.jpg media\user\profile\id_2\pic.jpg and so on... Would like to display the user's profile image only on their page when logged in. settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") root urls.py from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('index.urls')), ] if settings.DEBUG is True: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) index.html <div class="image"> <img src="{{ Theusers.image.url }}"/> </div> I think the problem is in the index.html? -
How to update multiple rows in MySQL (CASE, WHEN, THEN) using python/Django
I asked this question yesterday but It didn’t really help me. I am asking it again hoping my question is more clear this time. I am trying to update multiple rows in MySQL by using WHEN, THEN, ELSE case. I am trying to achieve this using python and Django in the backend. Here is my code: UPDATE priority SET priority_order = CASE priority_order WHEN 4 THEN 8 WHEN 1 THEN 4 WHEN 3 THEN 2 ## More X amount of WHEN/THEN statements ELSE priority_order END The problem is that I do not know how many WHEN and THEN lines I have.. How can I construct such a statement so that I can execute this using cursor.execute( )? Yesterday, someone advised to build a list of expression and pass as an argument like: from django.db.models import Case, When # Make a list of When expressions when_list = [When(priority_number=2, then=3), When(priority_number=3, then=4)] # Use in a query of your choice, as an example: Model.objects.update( priority_number=Case( *when_list)) But seems like it does not work on Mysql. I think this only works on SQLLite. The *when_list is not being decoded as my query execute. Please help! -
Nginx-proxy with SSL TLS handshake error
I'm trying to setup Nginx-proxy docker container made by Jwilder in combination the Letsencrypt companion container for ssl. behing the proxy is currently a single website that uses caddy as its server. Operating system is Ubuntu 16.04 and in the firewall I have opened the Ports 80 and 443. without Nginx-proxy I can connect to the website through HTTPS. But with nginx-proxy,I am unable to connect to the website through HTTPS. When I connect to is get the error, ERR_CONNECTION_REFUSED. I am out of idea's as to what could cause the error. docker-compose yml file: version: '2' volumes: postgres_data: {} postgres_backup: {} caddy: {} services: nginx-proxy: image: jwilder/nginx-proxy ports: - "80:80" - "443:443" volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - /path/to/certs:/etc/nginx/certs:rw - /etc/nginx/vhost.d - /usr/share/nginx/html labels: - com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy nginx-proxy-ssl-companion: image: jrcs/letsencrypt-nginx-proxy-companion volumes: - /var/run/docker.sock:/var/run/docker.sock:ro volumes_from: - nginx-proxy django: build: context: . dockerfile: ./compose/django/Dockerfile depends_on: - postgres - redis command: /gunicorn.sh env_file: .env postgres: build: ./compose/postgres volumes: - postgres_data:/var/lib/postgresql/data - postgres_backup:/backups env_file: .env caddy: build: ./compose/caddy depends_on: - django volumes: - caddy:/root/.caddy env_file: .env environment: - "VIRTUAL_HOST=www.mydomain.nl, mydomain.nl" expose: - 80 - 443 redis: image: redis:3.0 Logs: postgres_1 | LOG: database system was shut down at 2017-09-17 06:59:52 UTC postgres_1 | LOG: MultiXact member …