Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save data to database from Django Channels consumer
I'm having an hard time editing a database entry from a Django channels consumer, here is the piece of code involved: class TestConsumer(AsyncJsonWebsocketConsumer): async def websocket_connect(self, event): ... key_query.active_connections = 2 key_query.save() ... Since i'm using an asynchronous consumer, this will give me the following error: You cannot call this from an async context - use a thread or sync_to_async. How can i perform this action from an async consumer? Maybe using @database_sync_to_async?Any advice is appreciated! -
Django REST Framework - Adding 2 PKs in URL using Generic API Views
I am designing a REST API for an application that has Teams (Groups) and Members.This leads to the following API structure: /teams/api/ - Can GET, POST. (Done) /teams// - Can GET, POST, PUT, PATCH, DELETE. (Done) /teams/<teams_pk>/join/ - Can POST (Current Login User added in the Team). (Done) /teams/<teams_pk>/leave/ - Can DELETE.(Current User can leave the Team) (Remaining) /teams/<teams_pk>/leave/<member_pk>/ Can DELETE - (Admin Member Can Remove the Member) (Remaining) views.py class TeamMemberDestroyAPIView(generics.DestroyAPIView): queryset = TeamMember.objects.all() serializer_class = TeamMemberSerializer permission_classes = [IsAuthenticatedOrReadOnly] def perform_destroy(self, instance): team_pk = self.kwargs.get("team_pk") team = get_object_or_404(Team, pk=team_pk) joining_member = self.request.user.profile TeamMember.objects.filter(team=team, user=joining_member).delete() urls.py urlpatterns = [ path('api/', TeamListCreateAPIView.as_view()), path('api/<int:pk>/', TeamDetailAPIView.as_view()), path('api/<int:team_pk>/join/', TeamMemberCreateAPIView.as_view()), path('api/<int:team_pk>/leave/',TeamMemberDestroyAPIView.as_view()), ] serializers.py class TeamMemberSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(read_only=True) class Meta: model = TeamMember # fields = '__all__' exclude = ("team",) class TeamSerializer(serializers.ModelSerializer): admin = serializers.StringRelatedField(read_only=True) member = TeamMemberSerializer(many=True, read_only=True) class Meta: model = Team fields = '__all__' models.py class Team(models.Model): options = ( ('public', 'Public'), ('private', 'Private') ) admin = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name='team_admin') name = models.CharField(max_length=300) description = models.CharField(max_length=300, blank=True) privacy = models.CharField( max_length=240, choices=options, default="private") member = models.ManyToManyField( Profile, through='TeamMember', related_name='team_members') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: ordering = ['-created_at'] class TeamMember(models.Model): team = models.ForeignKey( Team, … -
Why is Django LoginView login not working?
I made a login form using Django ready LoginVew class, but idk why it isnot working. Here is the code views.py from django.shortcuts import render, redirect from django.contrib.auth import views as auth_views from django.contrib.auth.forms import AuthenticationForm def main(request): if request.method == 'POST': loginform = auth_views.LoginView.as_view(template_name='main/index.html') loginform(request) return redirect('signup') loginform = AuthenticationForm(request) return render(request, 'main/index.html', {'loginform': loginform}) urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.main, name='main'), path('signup/', include('signup.urls')), path('admin/', admin.site.urls), ] HTML <div class="log-outside"> <div class="log-inside"> {% csrf_token %} {{ loginform }} <button type="subbmit">Log in</button> </div> </div> -
How to refresh the form fields and view after a different app update's the database? Django, Python
I have 2 apps, 2 forms, the checkboxes in form 1 depend on the values stored in Model 2 (by form2). The problem is, when I add a new object in Model 2 (form 2), and go to Form 1, the checkboxes do not update. I've tried all i could, please let me know what I'm doing wrong, and if there's a way to achieve this. This if form-1, where the form fields depend on the distinct values of 'queue_names' present in the QueueStatusModel (a different app) class NewInvestigatorForm(forms.ModelForm): queues_queryset = QueueStatusModel.objects.order_by().values('queue_name').distinct() queue_name_list = [] for i in queues_queryset: x = i.get("queue_name") queue_name_list.append( (x,x) ) active_qs = forms.MultipleChoiceField( choices = queue_name_list, widget = forms.CheckboxSelectMultiple, ) class Meta: model = PriorityModel fields = [ 'login', 'core', 'active_qs', 'priority' ] This is form-2, where I add a new 'queue_name': class AddNewQueue(forms.ModelForm): queue_name = forms.CharField(widget=forms.TextInput(attrs={"placeholder":"Queue Name", "size":60})) class Meta: model = QueueStatusModel fields = [ 'queue_name' ] def clean_queue_name(self, *args, **kwargs): queue_name = self.cleaned_data.get("queue_name") if " " in queue_name: raise forms.ValidationError("Queue names cannot contain space") else: return queue_name Queue Status Model, where the queue related info is stored: class QueueStatusModel(models.Model): queue_name = models.CharField(max_length=100) volume = models.IntegerField() active_investigators = models.IntegerField() New Investigator related Model: … -
After upgrading to PostgreSQL default value for ImageField does not work (Django)
Since shifting to PostgreSQL (from SQLite) the default value for ImageField does not work. If I select and upload the image manually everything is fine. Also other fields default values work fine as well. This is done from admin while adding a new post. models.py: preview_content = models.TextField(max_length=150, default="This is the default preview") preview_image = models.ImageField(default="img/blog/default_preview.jpg", upload_to="img/blog") First one works fine, second one does not. Does anyone know what the problem is? -
Django: Show downloadable custom log file
I have a small Django Project, where the user can uplaod a csv file which is parsed to the Database. If there are some formating issues detected during the processing I write them into a pd.DataFrame and want to show them to the user afterwards, so they know which lines of the csv could not be processed correctly. I thought about a few ways to do this. I could create a custom model only for the log, but I want the user to be able to download the log, which is why I would prefer to save the Log to a csv and show a download Link as well as the content of the Log, but I don't know how to do it or if there is a better way? My Code looks something like this: class ListVerifyView(ListView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ... return context def post(self, request, *args, **kwargs): for k, v in request.POST.items(): try: col_dict[v] = int(k) except ValueError: pass ... error_log = pd.DataFrame(columns=['Chemical', 'Error']) ... if not error_log.empty: messages.add_message(self.request, messages.WARNING, 'Some ERRORS occurred during import!') return HttpResponseRedirect(reverse_lazy('show_error')) return HttpResponseRedirect(reverse_lazy('home')) I thought about saving the Log as a models.FileField and pass the pk to reverse_lazy('show_error') but … -
Render include tag with conditional variable
I have a sub-template that renders a typical table, based on a variable transaction_items, as following: <table id="order-list" class="order-list order-list-hoverable"> <thead> <tr class="w3-light-grey"> <th>Item</th> <th>Qty</th> <th>Total</th> </tr> </thead> <tbody> {% for transaction_item in transaction_items %} <tr id="order{{forloop.counter}}{{transaction_item.name}}" data-order_modal="{{transaction_item.name}}order{{forloop.counter}}"> <td>{{transaction_item.name}}</td> <td>{{transaction_item.quantity}}</td> <td>{{transaction_item.get_total_cost}}</td> </tr> {% endfor %} </tbody> </table> In a parent template, I would like to use include tag to call this template as following: {% include "order_summary.html" with transaction_items=transaction_items_N %} Suppose I have N buttons that, when clicked, return a variable transaction_items_N. I would like to immediately re-render the above table with the new transaction_items_N. How do I make the include tag accept this kind of dynamic variable-parsing in the template? Or mus this be done with JavaScript? Thanks. -
modify the value of paginate_by for all pages
I have a follow-up question on the answer to Change value for paginate_by on the fly I added the following in the HTML <form method="GET"> <select name="paginate_by" id=""> <option value="5">5</option> <option value="10">10</option> <option value="20">20</option> <option value="50">50</option> </select> <input type="submit" value="Paginate"> </form> and this function in my ListView class class ReviewPostListView(ListView): model = Reviews template_name = 'reviews/reviews.html' context_object_name = 'rows' ordering = ['id'] paginate_by = 5 def get_paginate_by(self, queryset): return self.request.GET.get("paginate_by", self.paginate_by) it is working great, and the paginate_by is added to the URL. My problem is when I click on the second page it goes back to 5. This is my pagination HTML {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info mb-4" href="?page={{ num }}">{{num}}</a> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{num}}</a> {% endif %} {% endfor %} {%if page_obj.has_next %} <a class="btn btn-outline-info mb-4" href="?page={{page_obj.next_page_number}}">Next</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a> {% endif %} {% endif %} What is the pythonic of keeping the paginate_by (if exists) parameter … -
Django app working on my system but not working on repl.it
So I created Django app: https://github.com/Paresh-Wadhwani/toDo_Django Then I imported the above repo to repl.it: https://repl.it/@pareshwadhwani/toDoDjango#README.md It is working perfectly fine on my system but on repl.it it is just showing a blank page. Here's what I did: Imported the codebase from Github into repl.it. Added the repl link to ALLOWED_HOSTS in settings.py. Executed the command "python manage.py migrate". Clicked Run [It executes the command "python manage.py runserver 0.0.0.0:3000"] Now on repl, it is just showing this blank page. ScreenShot I am new to Django and to Web Development. Any help would be appreciated. -
Unable to make a field optional in Django
I have updated my Address model to make the "State" field optional by adding blank=True and null=True. I now have the following: state = models.CharField(max_length=12, blank=True, null=True) I ran a migration for this as well, but I am still getting the following error when the form is submitted: {"errors": {"state": "This field is required."}} Where else would it be marked as being a required field? -
Initializing foriegnkey in CRUD operation
i am working on a project to manage animal farm. The backend is with django and the frot end is with bootstrap. The project has several apps as in django documentation. views.py from django.shortcuts import render,redirect, get_object_or_404 from django.http import JsonResponse from django.template.loader import render_to_string from django.urls import reverse_lazy from livestockrecords.models import * from .models import * from .forms import * from .models import * from .forms import * # Create your views here. def daily_home(request): context =() template = 'dailyrecords/daily_home.html' return render(request, template, context) > def save_feedin_form(request, form, template_name): > data = dict() > if request.method == 'POST': > if form.is_valid(): > form.save() > data['form_is_valid'] = True > livestocks = Livestock.objects.all() > context ={ > 'livestocks': livestocks > } > data['html_livestock_list'] = render_to_string('includes/_list_feeding.html', context) > else: > data['form_is_valid'] = False > context = {'form': form} > data['html_form'] = render_to_string(template_name, context, request=request) > return JsonResponse(data) def feeding_add(request, pk): livestocks = get_object_or_404(Livestock, pk=pk) data = dict() if request.method == 'POST': form = FeedingForm(request.POST , initial={'livestock': pk}) else: form = FeedingForm(initial={'livestock': livestocks}) return save_feedin_form(request, form, 'includes/_add_feeding.html') models.py from django.db import models from livestockrecords.models import Livestock # Create your models here. class Addmedication(models.Model): MEDICATIONTYPE = ( ('Drugs', 'Drugs'), ('Vaccination', 'Vaccination'), ) name = … -
how to start project with Django in powershell
I am new to web development with Python and after installing django I typed a command on powershell (on Windows): django-admin startproject mysite and it didn't work. I took this command from the Django site documentation -
Hi everybody. I'm making a shop with django and i have a problem with custom User
When I'm trying to delete my ShopUser i have this exception I have not found a solution to this problem on the internet Exception Type: OperationalError Exception Value: no such table: account_shopuser_groups Also this exception resises when I want to migrate. How can i solve this problem? My CustomUserModel: class ShopUser(AbstractUser): username = models.CharField( _('username'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), error_messages={ 'unique': _("A user with that username already exists."), }, ) email = models.EmailField(_('email address'), unique=True) EMAIL_FIELD = 'email' USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] is_superuser = models.BooleanField( _('superuser status'), default=False, help_text=_( 'Designates that this user has all permissions without ' 'explicitly assigning them.' ), ) objects = CustomUserManager() date_joined = models.DateTimeField(_('date joined'), default=timezone.now) def has_perm(self, perm, obj=None): return True def __str__(self): return self.username my CustomUserAdmin class ShopUserAdmin(UserAdmin): add_form = ShopUserCreationForm form = ShopUserChangeForm model = ShopUser list_display = ('email', 'is_staff', 'is_active',) list_filter = ('email', 'is_staff', 'is_active',) fieldsets = ( (None, {'fields': ('email', 'password',)}), ('Permissions', {'fields': ('is_staff', 'is_active')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2', 'is_staff', 'is_active')} ), ) search_fields = ('email',) ordering = ('email',) admin.site.register(ShopUser, ShopUserAdmin) Thank you for help! -
How to display just the tags in form instead of all the list elements in Django?
I have a form used to create and edit an object on Django, and I'm trying to implement tags with django-taggit and Crispy Forms. Currently it's working great to create the tags, and it creates a list of tags for the field. When I want to edit the object I get the field pre-populated with those tags, but they are not 'flattened', so the tags show as: [<Tag:Tag1> <Tag:Tag2> <Tag:Tag3>] rather than just Tag1 Tag2 Tag3 And if the object contains no tags there is [] in the form field. My view to edit the objects is: def edit_recipe(request, recipe_id): """Edit an existing recipe""" recipe = get_object_or_404(Recipe, pk=recipe_id) if request.method == "POST": form = RecipeForm(request.POST, request.FILES, instance=recipe) if form.is_valid(): form.save() messages.success(request, "Successfully updated recipe.") return redirect(reverse("recipes")) else: messages.error(request, "Failed to update. Please check the form.") else: form = RecipeForm(instance=recipe) template = "recipes/edit_recipe.html" context = {"form": form, "recipe": recipe} return render(request, template, context) My model includes the field tags as so: tags = TaggableManager(blank=True) And my form is: class RecipeForm(forms.ModelForm): class Meta: model = Recipe fields = ( ... "tags", ) widgets = {"tags": forms.TextInput(attrs={"data-role": "tagsinput"})} What do I need to do to populate the form to edit an already existing … -
How to create a table with django models inside the app?
my_api ├── admin.py ├── apps.py ├── heroes │ ├── admin.py │ ├── __init__.py`enter code here` │ ├── models.py │ ├── __pycache__ │ │ ├── admin.cpython-38.pyc │ │ ├── __init__.cpython-38.pyc │ │ ├── models.cpython-38.pyc │ │ ├── serializers.cpython-38.pyc │ │ └── views.cpython-38.pyc │ ├── serializers.py │ └── views.py ├── __init__.py ├── migrations │ ├── __init__.py │ └── __pycache__ │ └── __init__.cpython-38.pyc ├── models.py ├── __pycache__ │ ├── admin.cpython-38.pyc │ ├── apps.cpython-38.pyc │ ├── __init__.cpython-38.pyc │ ├── models.cpython-38.pyc │ ├── urls.cpython-38.pyc │ └── views.cpython-38.pyc ├── tests.py ├── urls.py ├── views.py I am trying to build a simple rest api with drf. created a directory heroes inside the my_api and created a new class. now my_api/heroes/models.py looks like this: class Hero(models.Model): name = models.CharField(max_length=50) power = models.CharField(max_length=100) my_fav = models.BooleanField() def __str__(self): return self.name The problem is, whenever I try to migrate this table doesn't get created. What should I change to make it work? -
Django blog app with comments using class views
I' wanted to try Django framework and i tried the blog app tutorial. i tried to add a comment feature. i know these questions have been asked several times but couldn't find a solution to my problem. i got 'No Post matches the given query' error. Thanks for your help. Here are the Model and all: urls.py : path('', PostListView.as_view(), name='blog-home'), path('user/<str:username>/', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('post/<int:pk>/comment/', PostCommentView.as_view(), name='post-comment'), path('about/', views.about, name='blog-about'), ] models.py: class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) # many to one relation use foreign key def __str__(self): return self.title @property def get_comments(self): return self.comment_content.all() # return the url as string def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Comment(models.Model): content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, related_name='comment_content', on_delete=models.CASCADE) def __str__(self): return self.content def get_absolute_url(self): return reverse('comment-create', kwargs={'pk': self.pk}) forms.py: class CommentForm(forms.ModelForm): content=forms.Textarea() class Meta: model = Comment fields=['content'] views.py: class PostCommentView(LoginRequiredMixin, CreateView): model = Comment fields = ['content'] template_name = 'blog/comment_form.html' success_url = '/' def form_valid(self, form): post = get_object_or_404(Post, id=self.kwargs.get('id')) print(post.id) form.instance.author = self.request.user form.instance.post = post return super().form_valid(form) comment_form.htlm: {% extends … -
Can't login to django admin with correct credentials
I can't login to my django admin side even after puting correct credentials. It gives me the error... "Please enter the correct email and password of a staff account. Note that both fields may be case sensitive." And yes, the credentials is a superuser, a staff and active. I use a custom authentication backend and my version is Django 2.2 -
How to create relative entry in mongoldb using Django?
I have following Person document model. from djongo import models from django.contrib.postgres.fields import ArrayField class Person(models.Model): id = models.ObjectIdField() name = models.CharField(max_length=255) city = models.CharField(max_length=255) status = models.CharField(max_length=20) phone_number = models.CharField(max_length=20) objects = models.DjongoManager() And the following Comment model class Comment: id = models.OneToOneField( Person, on_delete=models.CASCADE, primary_key=True, ) comments = ArrayField(models.CharField()) objects = models.DjongoManager() When I create a document in Person object, I want mongo automatically create a document in Comment model with the same id but empty comments. I thought declaring OneToOneField filed will do it, but it didn't. What should I do? -
Get env variable from heroku
I have django project on heroku. On my Procfile i use 'release: bach./releast-tasks.sh' that will generate new env variable. web: gunicorn billions.wsgi --log-file - release: bash ./release-tasks.sh Here my release-tasks.sh: #!/bin/sh electrum daemon -d electrum setconfig rpcport 7777 pass=$(electrum getconfig rpcpassword) echo $pass export RPCPASSWORD=$pass The deploy (git push heroku master) is working fine and perfectly. I do not get any error. But now on my code i try to get "RPCPASSWORD" env variable like that : logger.info(os.environ.get('RPCPASSWORD', 'None')) It's alaways returning None. So 2 problems : I am not sure the env variable is really set with release-tasks.sh If it's correctly set, why i can't grab it with my django code :/ ? Thank for your help ! -
Add CSS to form field in django template
I want to use bootstrap on django form. To do so I need to add .form-control class to each field. My workaround is: def __init__(self, *args, **kwargs): super(SomeForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs = { 'class': 'form-control' } {% for field in form %} <div class="form-group"> {{ field.label_tag }} {{ field }} </div> {% endfor %} But I believe it's wrong to put CSS in python code (if I would want to use another CSS framework, I would have to change form class). How can I move the class to template? I would not like to use crispy not to be bound to bootstrap. -
TinyMCE with DigitalOcean Space in Django
I am currently working on building blog site using django and DigitalOcean Space. I've connected everything so static and media files automatically get saved to DigitalOcean space. However, I've been trying to get images in content (TinyMCE HTMLField()) get saved to DigitalOcean Space but seems to be not working. If I drag and drop the image to TinyMCE richtext area, it gets img src from my local path. If I do Upload, Source address seems to be generated with right path, but it's not saving the images to Space. I currently have In settings.py, TINYMCE_DEFAULT_CONFIG 'images_upload_url': '/upload_image/' In views.py, @csrf_exempt def upload_image(request): if request.method == "POST": file_obj = request.FILES['file'] file_name_suffix = file_obj.name.split(".")[-1] if file_name_suffix not in ["jpg", "png", "gif", "jpeg", ]: return JsonResponse({"message": "Wrong file format"}) upload_time = timezone.now() path = os.path.join( settings.MEDIA_ROOT, 'tinymce', str(upload_time.year), str(upload_time.month), str(upload_time.day) ) # If there is no such path, create if not os.path.exists(path): os.makedirs(path) file_path = os.path.join(path, file_obj.name) file_url = f'{settings.MEDIA_URL}tinymce/{upload_time.year}/{upload_time.month}/{upload_time.day}/{file_obj.name}' client.upload_file('file_obj', 'blmakerspace-spaces', 'file_url') if os.path.exists(file_path): return JsonResponse({ "message": "file already exist", 'location': file_url }) with open(file_path, 'wb+') as f: for chunk in file_obj.chunks(): f.write(chunk) return JsonResponse({ 'message': 'Image uploaded successfully', 'location': file_url }) return JsonResponse({'detail': "Wrong request"}) and urls.py set to path('upload_image/', upload_image) … -
I feel lost with Django in every possible way
I am new to stack overflow so feel free to criticise if this ain't the kind of post to put on here, but I really don't know where else to ask then here where population is so big. I don't know how to start django project of my own.Yes I watched tutorials, got myself cheat sheets for django and html and am currently doing guide which explains things step by step and am doing and trying to understand as much as possible. The problem is even with all this, I've got only as far as navigating and making new directory with command prompt, loading virtual environment, running server and opening shell. I get the idea behind all the code in the guide that was written and what each line does but if you asked me to make a basic website on my own I wouldn't be able to do anything besides setting up the environment. Is there like a pattern to follow when making shit from scratch and do beginners like me even do anything from scratch or what? I have some great ideas, and while I do love coding, I am learning django for purpose of making my own … -
Custom Form Field Naming Within Loop
I'm trying to specify field names within a loop on a form, so that the fields do not overwrite themselves. Right now I'm using this in my form: class TicketForm(forms.ModelForm): class Meta: model = Ticket exclude = ['products'] class ProductForm(forms.Form): product_id = forms.IntegerField() count = forms.IntegerField() class TicketProductForm(forms.ModelForm): class Meta: model = Ticket exclude = [] for Product in Product.objects.all(): product_id = forms.IntegerField(initial=Product.product_id) count = forms.IntegerField(initial=0) The for loop within TicketProductForm currently only displays one set of fields, as product_id and count overwrite the fields over and over, only displaying for the last entry in the set of Product. Is there a way to customize field names so that I can name them, preferably with a way I can set a specifier to allow easier lookup later? -
Django admin panel does not display correctly
Good evening, I taught the django framework at the rate. Before that, the admin panel was displayed correctly, now for some reason it is displayed as I understood without css styles Default django server, writing code in pycharm And before it was displayed like this settings.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*ky(o6p+iw1(8u4fx$^fwnpdqt337(yw3*uk%g02b3*8(x-av$' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'news.apps.NewsConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': … -
How to run Django and Celery in separated Docker container?
I want to have two containers - one for my Django app and one for the Celery that the Django app uses. Those two containers have the same code. In my tasks.py file I have: app = Celery('myapp', broker=settings.CELERY_BROKER, backend=settings.CELERY_BACKEND) Where broker is a URL to redis. The way I start my celery app: docker build -f Dockerfile.celery -t celery_app . docker run -d -p 80002:8000 celery_app The way I start my django app: docker build -f Dockerfile.django -t django_app . docker run -d -p 8000:8000 django_app What should be CELERY_BACKEND to make it work?