Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail Create Snippet from the frontend to accepts Images (Django)
I have a simple snippet using Django Wagtail. I would like to be able to update the logo from a "CreateView" but when it renders in my view it's expecting a foreign key. I would imagine it would be easy to create a from to do this but it's not. @register_snippet class MerchantSnippet(models.Model): name = models.CharField(max_length=255, blank=False, null=False, unique=True) logo = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, ) def __str__(self): return '{} {}'.format(self.user.first_name, self.user.last_name) panels =[ FieldPanel('name'), ImageChooserPanel('logo'), ] edit_handler = TabbedInterface([ ObjectList(panels, heading='Content'), ]) class ProductCreateView(CreateView): model = ProductSnippet fields = ['name','logo'] class ProductUpdateView(UpdateView): model = ProductSnippet fields = ['name','logo'] When I use the default example in the template I ended up just getting a drop down. {% render_field field class+="form-control" %} How would I be able to see an image preview in the event I am updating the snippet and the ability to upload a different one . In the event I am creating a new item the ability to select an upload an image. -
Iterating over model object in template is returning no results - Django
This is my model: pass class Listing(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=500) url = models.URLField() live = models.BooleanField(default=True) author = models.ForeignKey('User', on_delete=models.CASCADE, name='author') category = models.ForeignKey('Category', on_delete=models.CASCADE, name='category', default="") def __str__(self): return f'{self.id}: {self.title}' class Bid(models.Model): price = models.DecimalField(decimal_places=2, max_digits=10) bid_count = models.IntegerField() highest_bidder = models.ForeignKey('User', on_delete=models.PROTECT, name="highest_bidder", default=None, blank=True, null=True) listing = models.ForeignKey('Listing', on_delete=models.CASCADE, name='listing', default="") def __str__(self): return f'{self.listing.title} ({self.price})' class Category(models.Model): title = models.CharField(max_length=200) def __str__(self): return self.title class Watchlist(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE, name='user') item = models.ManyToManyField('Listing', blank=True, null=True) def __str__(self): return f"{self.user}'s Watchlist" This is my view: currentUser = request.user watchlist = Watchlist.objects.filter(user=request.user).values() bids = Bid.objects.all() return render(request, 'auctions/userWatchlist.html', { 'currentUser': currentUser, 'watchlist': watchlist, 'bids': bids }) I've also tried not passing in .values() and using .all in the template instead. Here's the template: {% block body %} <h2>Watchlist</h2> <div class="container"> <div class="row"> {% for listing in watchlist %} <div>{{ listing }}</div> <div class="col"> <div class="card" style="width: 18rem;"> <img src="{{ listing.item.url }}" class="card-img-top" alt="{{ listing.item.title }}"> <div class="card-body"> <h5 class="card-title">{{ listing.item.title }}</h5> <p class="card-text">{{ listing.item.description }}</p> {% for bid in bids.all %} {% if bid.listing == listing.item %} <p class="card-text">Bid price: {{ bid.price }}</p> {% endif %} {% endfor %} <a href="{% url 'item_details' … -
Django Many to Many relationship Query Filter
class servers(models.Model): hostname=models.CharField(max_length=100) ip= models.CharField(max_length=100) os= models.CharField(max_length=100) class application(models.Model) name=models.CharField(max_length=100) URL= models.CharField(max_length=100) servers= models.ManyToManyField(servers, blank = True, null=True) current DB status 3 servers 2 with os as linux and 1 with os as windows 2 applications Requirement : application can have many servers and each server can be part of many applications also Need support to create filter only those applications whose os is windows. I tried below but it is returning all three servers. def viewapp(request,pk) criterion1 = Q(id=pk) criterion2 = Q(servers__os__startswith="windows") prodlist = application.objects.filter(criterion1 & criterion2) -
how I'm gonna create the URL pattern for each topic?
I want to create a URL patterns for each topic. How I'm gonna do that?? This is my code: models.py from django.db import models from django.db import models class Task(models.Model): title = models.CharField(max_length=50) completed = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title urls.py from django.urls import path from . import views app_name = 'my_app' urlpatterns = [ path('', views.index, name='index'), path('add_task/', views.add_task, name='add_task'), ] forms.py from django import forms from .models import Task class TaskForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'add new task...'})) class Meta: model = Task fields = '__all__' views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Task from .forms import TaskForm def index(request): task = Task.objects.all() context = {'task': task} return render(request, 'my_app/index.html', context) def add_task(request): if request.method == 'GET': form = TaskForm() else: form = TaskForm(data=request.POST) if form.is_valid(): form.save() return redirect('my_app:index') context = {'form': form} return render(request, 'my_app/add_task.html', context) base.html To do {% block content %}{% endblock %} index.html {% extends 'my_app/base.html' %} {% block content %} <p><a href="{% url 'my_app:add_task' %}">Add task</a></p> <ul> {% for tasks in task %} <li> {{ tasks }} </li> {% empty %} <li> <p>There's no task</p> </li> {% endfor %} </ul> {% endblock %} add_task.html {% … -
how to save the uploaded images in Django backend
Here I have written a code for multi uploading images. This I have done in vue.js and backend is Django. So here while user uploads an multiple images so it is uploading the image and it is showing in console. But the issue i am not able to access this in backend. And below I have past django function if anyone have an idea how to save this images in backend from last one week struggling alot to save the images in backend nut not succeeded yet please help me if anyone have an idea about this <body> <div id="el"> <div id="my-strictly-unique-vue-upload-multiple-image"> <vue-upload-multiple-image @upload-success="uploadImageSuccess" @before-remove="beforeRemove" @edit-image="editImage" @data-change="dataChange" :data-images="images" ></vue-upload-multiple-image> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script> <script src="https://unpkg.com/vue-upload-multiple-image@1.0.2/dist/vue-upload-multiple-image.js"></script> <script type="text/javascript"> var vm = new Vue({ el: '#el', data() { return { images: [] } }, components: { VueUploadMultipleImage, }, methods: { uploadImageSuccess(formData, index, fileList) { console.log('data k', fileList); console.log('data1', formData); console.log('data2', index); }, beforeRemove(index, done, fileList) { console.log('index', index, fileList) var r = confirm("remove image") if (r == true) { done() } else { } }, editImage(formData, index, fileList) { console.log('edit data', formData, index, fileList) }, dataChange(data) { console.log(data); } } }); </script> </body> views.py def fileupload(request): return render(request, 'fileupload.html') -
Using User Model in POST Django Rest Framework
I have a small web app. I want to essentially recreate this form from django admin, in a POST request in Django REST Framework: I've been able to add the File Name and File Path fields, but I am have trouble replicating the user field so I can type in a user id or user name and send it with the request. I keep getting this is error when I access the endpoint: django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field I have included my serializer and view for the endpoint below: serializer.py class FileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = File fields = '__all__' views.py class UserFileList(generics.ListCreateAPIView): queryset = File.objects.all().order_by('user_id') permisson_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = FileSerializer -
How to make calculation of fields from different Models?
There are now three tables: class Product(models.Model): sku = models.CharField(max_length=200, unique=True) name = models.CharField(max_length=200, null=True) class HistoricalData(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) date = models.DateTimeField() demand_sold = models.IntegerField(default=0) class ForecastData(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) date = models.DateTimeField() demand_sold = models.IntegerField(default=0) I need to compare Historical and Forecast data for the list of products and calculate the accuracy rate. Formula like: ForecastData.demand_sold * 100/HistoricalData.demand_sold The current solution is to iterate through the history and forecast datasets and make calculations for demand_sold products = Product.objects.filter(...) queryset_hist = HistoricalData.objects.filter(product__in=products) queryset_forecast = ForecastData.objects.filter(product__in=products) I am wondering is there any elegant solution to calculate field from different Django Models. -
How to implement elastic search using graphene-elastic in Django?
Hope you all are having an amazing day ! I’m trying to implement elastic search in my Django application using graphene-elastic package https://graphene-elastic.readthedocs.io/en/latest/ and documentation for this is quite unclear what I want to achieve, Any leads to working examples or blogs would be very much appreciated! Thanks :) -
How to encrypt postgresql database with Django as the backend?
I am using Postgresql database with Django rest framework, I want to encrypt my database to improve security but I didn't find any documentations which clearly explains the encryption process and algorithms underlying it. Any help is appreciated -
How can I do additions of multiple values in Django template?
1 <div class="row"> <div class="col-7 text-start fs2 border-bottom border-dark"><b>RT CASH AMOUNT</b></div> <div class="col-3 text-center fs2 border-start border-bottom border-dark"><b>KCC</b></div> <div class="col-2 text-center fs2 border-start border-bottom border-dark" id="cash_amt"> <b> {% if total1.realization__amount_received__sum == None %} 0 {% else %} {{total1.realization__amount_received__sum|floatformat}} {% endif %} </b> </div> </div> 2 <div class="row"> <div class="col-7 text-start fs2 border-bottom border-dark"><b>RT CASH AMOUNT</b></div> <div class="col-3 text-center fs2 border-start border-bottom border-dark"><b>KCC</b></div> <div class="col-2 text-center fs2 border-start border-bottom border-dark" id="cash_amt"> <b> {% if total2.realization__amount_received__sum == None %} 0 {% else %} {{total2.realization__amount_received__sum|floatformat}} {% endif %} </b> </div> </div> 3 <div class="row"> <div class="col-7 text-start fs2 border-bottom border-dark"><b>RT CASH AMOUNT</b></div> <div class="col-3 text-center fs2 border-start border-bottom border-dark"><b>KCC</b></div> <div class="col-2 text-center fs2 border-start border-bottom border-dark" id="cash_amt"> <b> {% if total3.realization__amount_received__sum == None %} 0 {% else %} {{total3.realization__amount_received__sum|floatformat}} {% endif %} </b> </div> </div> 4 <div class="row"> <div class="col-7 text-start fs2 border-bottom border-dark"><b>RT CASH AMOUNT</b></div> <div class="col-3 text-center fs2 border-start border-bottom border-dark"><b>KCC</b></div> <div class="col-2 text-center fs2 border-start border-bottom border-dark" id="cash_amt"> <b> {% if total4.realization__amount_received__sum == None %} 0 {% else %} {{total4.realization__amount_received__sum|floatformat}} {% endif %} </b> </div> </div> And where I want the result: <div class="row"> <div class="col-7 text-start fs2 border-bottom border-dark"></div> <div class="col-3 text-center fs2 border-start border-bottom border-dark"><b>TOTAL (A)</b></div> <div class="col-2 … -
Returning only one value from the database in Django
I'm trying to retrieve the data from the SQL stored procedure where I'm able to get the data but its giving the single output but I want to reflect all the records from the database. How could I loop through each one of the element in the database views.py: @api_view(['GET', 'POST']) def ClaimReferenceView(request,userid): try: userid = Tblclaimreference.objects.filter(userid=userid) except Tblclaimreference.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': userID = request.data.get(userid) print(userID) cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetClaims] @UserId= %s',('10',)) result_set = cursor.fetchall() print(type(result_set)) print(result_set) for row in result_set: Number= row[0] Opened = row[1] Contacttype = row[2] Category1 = row[3] State = row[4] Assignmentgroup = row[5] Country_Location = row[6] Openedfor = row[7] Employeenumber = row[8] Shortdescription = row[9] AllocatedDate = row[10] return Response(result_set) return Response({"Number":Number,"Opened":Opened, "Contacttype": Contacttype, "Category1":Category1, "State":State, "Assignmentgroup":Assignmentgroup, "Country_Location": Country_Location, "Openedfor":Openedfor, "Employeenumber":Employeenumber, "Shortdescription": Shortdescription, "AllocatedDate":AllocatedDate}, status=status.HTTP_200_OK) elif request.method == 'POST': serializer = ClaimReferenceSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) output which I get only record but I want all the records to be printed AllocatedDate: "2021-11-10" Assignmentgroup: "BusS" Category1: "Referrals " Contacttype: "Web" Country_Location: "India" Employeenumber: 11546124 Number: "HRR6712929" Opened: "2021-11-05T20:22:58" Openedfor: "ritika" Shortdescription: "Unable to submit " State: "Draft" Data which I get from the database [(('HR749', datetime.datetime(2021, … -
Tests for view names failing since upgrading to Django 4.0
In a Django project I have tests that check that a URL uses a specific class-based view. e.g. I have this view: from django.views.generic import TemplateView class HomeView(TemplateView): template_name = "home.html" And this test: from django.test import TestCase from django.urls import resolve from myapp import views class UrlsTestCase(TestCase): def test_home_view(self): self.assertEqual(resolve("/").func.__name__, views.HomeView.__name__) This test passes in Django 3.x but once I try it with Django 4.0 the test fails with: self.assertEqual(resolve("/").func.__name__, views.HomeView.__name__) AssertionError: 'view' != 'HomeView' - view + HomeView Obviously something has changed in Django 4.0 but I can't see anything related in the release notes. So, what's changed and how can I make this test work again (or how can I test this in a better way)? -
Difference between post method and form_valid in generic base view
Can you explain me what is difference between two methods based on generic base view in Django: post and form_valid? I have both in my views, and both save my forms. I used it both, because my practical task required it, but understanding the difference between them I have no. Here's a part of my views.py. I hope you can shed some light on this question. class SellerUpdateView(LoginRequiredMixin, UpdateView): model = Seller template_name = "main/seller_update.html" fields = "__all__" success_url = reverse_lazy("seller-info") login_url = "/accounts/login/" def get_object(self, queryset=None): seller, created = Seller.objects.get_or_create(user=self.request.user) return seller def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["user_form"] = UserForm(instance=self.object.user) context["smslog_form"] = SMSLogForm(instance=self.object) return context def form_valid(self, form): self.object = form.save() user_form = UserForm(self.request.POST, instance=self.request.user) if user_form.is_valid(): user_form.save() return super().form_valid(form) class AdUpdateView(LoginRequiredMixin, UpdateView): model = Ad template_name = "main/update_ad.html" fields = ("name", "description", "category", "tag", "price") login_url = "/accounts/login/" def get_context_data(self): context = super().get_context_data() context["picture_form"] = ImageFormset(instance=self.object) context["seller"] = self.object.seller return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() formset = ImageFormset(request.POST, request.FILES, instance=self.object) if form.is_valid(): form.save() if formset.is_valid(): formset.save() return HttpResponseRedirect(self.get_success_url()) else: return form.invalid() def get_success_url(self): return reverse_lazy("ad-detail", args=(self.object.id,)) -
datetime as a parameter of stored procedure
I have this code snippet with a stored procedure Read_records_from_to cleaned_data = from_to_form.cleaned_data with connections["mssql_database"].cursor() as cursor: cursor.execute("Read_records_from_to '2021-12-01 07:55:39.000', '2021-12-14 07:55:39.000'") result = cursor.fetchall() class FromToForm(Form): start_date = DateField(widget=AdminDateWidget()) start_time = TimeField(widget=AdminTimeWidget()) end_date = DateField(widget=AdminDateWidget()) end_time = TimeField(widget=AdminTimeWidget()) The stored procedure takes to parameters from_datetime and to_datetime. I'd like to assign it values taken from FromtoForm. How can I do this? -
Django Models Save models with Variable Value
My Problem is the following: I want to have a list of counter models. These models have a property named "counter". I could just add a new counter model, but i think this is very inefficient, because every time I'm referring to a counter model with a ForeignKey that isn't already existing, I would have to add a new one. Is there a way to save memory like saving a list of models in another model to save memory and database space? -
Why using Django and React requires so much extra packages?
I have been going through a tutorial (https://www.youtube.com/watch?v=GieYIzvdt2U) where you have to use Babel, Webpack, and Redux which are all complicated in their regards. Why we can not use "djangorestframework" as my API and get the information using that API from React using JS. What do I gain using all these packages or I can not simply use what I am suggesting? -
creating an login page with user Authentication & this happened : raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
New in django. learning how to create an login with user Authentication .all thing is working correctly but when I putt wrong password for checking that the loop is working properly or not .Know that the error is due to wrong assignment of url, but can't understand how to solve it. I am using two apps one for login(name=trevalo_app) and second for all (name=MYapp) trevalo_app/views.py from django.shortcuts import render,redirect from django.http import * from django.contrib.auth import authenticate,login,logout from django.contrib import messages from .models import * def login_user(request): if request.method=='POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('index') else: messages.success(request,('There was an error in logining. Please Try again...')) return redirect('login') else: return render(request,'login_user.html',{}) MYapp/index.html <body> {% include 'MYapp/navebar.html' %} <center> <h1>{{name}}</h1> </center> <div class="cotainer"> {% if messages %} {% for message in messages %} {{message}} {% endfor %} {% endif %} </div> {% block content %} {% endblock content %} {% include 'MYapp/footer.html' %} </body> trevalo_app/urls.py from django.urls import path,include from . import views urlpatterns = [ path('login_user', views.login_user,name='login_user'), ] MYapp/urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.index, name … -
django redirects to LoginView page instead of ListView page
I set up login and logout functions on my website. I am using Django 3.2. I used class based views like below to create login, logout and list views: class UpdatedLoginView(LoginView): form_class = LoginForm template_name = 'user/login.html' redirect_field_name='main/homepage.html' def form_valid(self, form): remember_me = form.cleaned_data['remember_me'] if not remember_me: self.request.session.set_expiry(0) self.request.session.modified = True return super(UpdatedLoginView, self).form_valid(form) class MyLogoutView(LogoutView): template_name = 'user/logout.html' The website I am trying to access is connected to this view: class ArticleListView(LoginRequiredMixin, ListView): template_name = 'hal/ArticleListView.html' model = Article paginate_by = 5 queryset = Article.objects.filter(status=1) def get_context_data(self, **kwargs): context = super(ArticleListView, self).get_context_data(**kwargs) categories = Category.objects.all() context['categories'] = categories return context my url.py looks like this: urlpatterns = [ path('login/', views.UpdatedLoginView.as_view(), name='login'), path('logout/', views.MyLogoutView.as_view(), name='logout'), path('articles/', views.ArticleListView.as_view(), name='article_list'), ] My settings.py file LOGIN_URL = 'login' LOGIN_REDIRECT_URL = 'homepage' LOGOUT_REDIRECT_URL = 'homepage' I can succesfully log in and access homepage, however when I am trying to access articles/ page with list of articles instead of accessing this page I am being redirected to login page. My url after redirect looks like this: http://127.0.0.1:8000/login/?next=/articles/. I am quite new to Django and I am probably missing something. I read Django 3.2 documentation but I didn't find any answers. When I delete LoginRequiredMixin from … -
Sending data from React using Axios to Django - Post request is empty
I am trying to send data from React via axios to the Django. Here is the code on the React Side: axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true sendData = () => { let formData = new FormData() formData.append('picture', this.state.files.height, this.state.files.name) axios.post("/api/async_image_analyze/", formData, { headers: { 'accept': 'application/json','content-type': 'multipart/form-data' },}).then(resp => { console.log(resp)}) } Here is the code on Django Side: def image_algorithm(request, *args, **kwargs): if request.method == 'POST': print(json.loads(request.POST.get('picture'))) Basically, the request.POST.get is empty. Can someone help on why it is empty? -
How to create model with relationship one-to-many in Django?
I need create relationship one-to-many. One Group can have many members. Did I do it right? Model: class Group(models.Model): id = models.BigAutoField(primary_key=True) groupName: models.CharField(max_length=100) description: models.CharField(max_length=255) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) members: models.ForeignKey(User, n_delete=models.CASCADE) -
how to display django search result in new page
i want to display my django search result on a new html page instead of the page where the search bar is. i have tried manipulating my form tag and it still does'nt redirect to the page when i search, rather it stays on the same page. index.html <form action="{% url 'elements:all-elements' %}" method="get"> <input type="text" class="form-control" name="q" value="{{ request.GET.q }}" type="text" placeholder="Search Free Web Elements and Resources"> <button type="submit" class="btn bt-round" ><b><i class="bi bi-search"></i></b></button> </form> views.py - this is the view handling the seach, i dont know if anything would be appended there # Search Function query = request.GET.get("q") if query: vectors = vectors.filter( Q(title__icontains=query)).distinct() -
raise TypeError( TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use order_item.set() instead
When I'm trying to make serializer for my model to save order items i got this error This is my serializer class OrdersItemsSerializer(serializers.ModelSerializer): class Meta: model = OrderItems fields = ["customer","product","quantity"] class OrdersSerializer(serializers.ModelSerializer): order_item = OrdersItemsSerializer(many = True) class Meta: model = Orders fields = ["id","order_at","customer","total_price","diliver_at","order_item"] def save(self): order_item = self.validated_data.pop('order_item') orderitemsls=set() for f in order_item: orderitems=OrderItems( customer=f['customer'], product=f['product'], quantity=f['quantity'], ) orderitems.save() print(orderitems.id) orderitemsls.add(orderitems) print(orderitemsls) new_order=Orders( customer=self.validated_data['customer'], total_price=self.validated_data['total_price'], order_item=orderitemsls ) return orderitemsls This is my models from django.db import models from django.contrib.auth import get_user_model # Create your models here. User = get_user_model() class Customers(models.Model): customer = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField() phone=models.CharField(max_length=12) address=models.CharField(max_length=500) reg_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = "Customers" unique_together = ('customer', 'id') def __str__(self): return self.customer.username class Categories(models.Model): name = models.CharField(max_length=100) image = models.ImageField() reg_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Vendors(models.Model): vendor = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField() phone=models.CharField(max_length=12) address=models.CharField(max_length=500) reg_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = "Vendors" def __str__(self): return self.vendor.username class Products(models.Model): name = models.CharField(max_length=100) image = models.ImageField() price=models.IntegerField() vendor = models.ForeignKey(Vendors, on_delete=models.CASCADE) reg_at = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(Categories, on_delete=models.CASCADE) class Meta: verbose_name_plural = "Products" def __str__(self): return self.name class OrderItems(models.Model) : customer = models.ForeignKey(Customers, on_delete=models.CASCADE) ordered = … -
Best Practice to prevent form abuse Django
What is the best way to limit form submissions in Django? The form should be only submitted 5 times from the same IP in one hour, is there a way to do that in Django? I tried Django Ratelimit but it doesn't really work, because the traffic doesn't get blocked. -
How to update replicated Docker service
I'm still learning Docker, and unfortunately, after hours of reading its docs and trying various approaches, I need to ask for help here. I have 3 Droplets on Digital Ocean - dev, staging and production. They host a Django application and a database. Both dev and staging have one container, which is simply a Python container, and one MySQL container. I update them by pulling changes from a Bitbucket repository, applying migrations using docker exec -ti CONTAINER /bin/bash and restarting the Python container. The production Droplet has a replicated service and the image pulled from the container registry on Digital Ocean. I pull changes from the repository on Bitbucket, but because I can't simply restart the container, the changes are not reflected on the website. I tried docker stack deploy -c docker-compose.yml SERVICE --with-registry-auth and docker service update --image IMAGE SERVICE, but no effect. Any help would be appreciated. Thanks -
Django-restQL Vs Graphene-django
I recently stumbled upon 2 different Django libraries for graphql API development: Django-restQL and Graphene-django. I know they are fundamentally different, but in the end, they are both necessary for the development more precise GraphQL API compared to rest. That said, I'd love to know the challenges, special quirks and tweaks both frameworks have, and which would be "best" for the job.