Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Paginator - If there are more than ten posts, a “Next” button should appear
How can I detect in my JavaScript how many posts are there if my views method only sends 10 every time? basically, my all posts length is in the views.py method..But I need to know how many So I can add a next button if there are more than 10 posts. views.py def show_posts(request): all_posts = NewPost.objects.all() all_posts = all_posts.order_by("-date_added").all() paginator = Paginator(all_posts, 10) page_number = request.GET.get('page', 1) page_obj = paginator.get_page(page_number) return JsonResponse([website_post.serialize() for website_post in page_obj], safe=False) index.js function load_posts(){ document.querySelector('#page-view').style.display = 'none'; document.querySelector('#load-profile').style.display = 'none'; document.querySelector('#posts-view').style.display = 'block'; document.querySelector('#show-posts').style.display = 'block'; document.querySelector('#post-form').onsubmit = function() { compose_post(); } fetch('/posts/all_posts') // url with that API .then(response => response.json()) .then(all_posts => { // Loop and show all the posts. console.log(all_posts.length) all_posts.forEach(function(post) { // loop to loop over each object build_post(post) }); }); document.querySelector('#show-posts').innerHTML = "" } urls.py # API Routes path("posts/all_posts", views.show_posts, name="show_posts"), -
How to export information displayed in the template table to excel Django
I tried to export the information I display in the template under the table tag to excel, and the information was pulled from the SQL server. However, the exported csv only has headers in the file, I was wondering if anyone knows what might cause this? Here's my template: <body> <a href="{% url 'export_csv' %}">Export all PPs</a> <table class="myTable" id="myTable"> <center> <thead> <tr> <th>id</th> <th>Tracking Number</th> <th>Delivery Date</th> <th>Delivered</th> </tr> </thead> <tbody> {% for display in Project %} <tr> <td>{{display.id}}</td> <td>{{display.TrackingNumber}}</td> <td>{{display.EstimatedDeliveryDate}}</td> <td>{{display.Delivered}}</td> </tr> {% endfor %} </tbody> </center> </table> </body> Here's my model.py: id = models.CharField(max_length=1000) TrackingNumber = models.CharField(max_length=1000) EstimatedDeliveryDate = models.DateField(max_length=25) Delivered = models.CharField(max_length=1000) Here's my views.py: conn_Project = pyodbc.connect('driver={sql server};' 'server=test;' 'Database=test;' 'Trusted_Connection=yes;') cursor_Project = conn_Project.cursor() selectedpp_p = request.POST.get('selectedpp_p', None) query_Project = """select id,TrackingNumber,EstimatedDeliveryDate,Delivered from Test.Project where Project = ?""" cursor_Project.execute( query_Project, selectedpp_p ) result_Project = cursor_Project.fetchall() return render(request, 'introduction/project.html', {'Project': result_Project, 'selected_project': selected_project}) def export_csv_p(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=Exported Table' + \ str(datetime.datetime.now())+'.csv' writer = csv.writer(response) writer.writerow(['ID', 'TrackingNumber', 'DeliveryDate', 'Delivered']) for project in Project.objects.all().values_list('ID', 'TrackingNumber', 'DeliveryDate', 'Delivered'): writer.writerow(project) return response Here's my url.py: path('admin/', admin.site.urls), path('', introduction.views.project, name='project'), url(r'^export/csv/project/$', introduction.views.export_csv_p, name='export_csv_p'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Thank you in advance! -
Django unit test - patch multiple requests for external api
I need to write 'one' test code with external api, which requires requests 'twice'. first, I need to check if user is valid. So I handled this with decorator in ./users/utils.py import requests def login_decorator(func): def wrapper(self, request, *args, **kwargs): # this access token is issued by external api access_token = request.headers.get('Authorization', None) # first requests, which gives me an info about user. response = requests.get( 'https://kapi.kakao.com/v2/user/me', headers={'Authorization':f'Bearer {access_token}'} ) user_email = response.json()['kakao_account']['email'] request.user = User.objects.get(email=user_email) return func(self, request, *args, **kwargs) return wrapper and then, I need to send that user a message with the external api again. this code is in ./bids/views.py import requests class BiddingView(View): #it uses login_decorator above @login_decorator def post(self, request, art_id): try: user = request.user data = json.loads(request.body) with transaction.atomic(): #handle things with bidding system# #the external api requires its token to use a message api. token = request.headers.get('Authorization', None) #second requests, with post method response = requests.post( 'https://kapi.kakao.com/v2/api/talk/memo/default/send', headers = {'Authorization' : f'Bearer {token}'}, data = {"template_object" : json.dumps({'message':'contents'})} ) return JsonResponse({'MESSAGE' : 'SUCCESS'}, status=200) except KeyError: return JsonResponse({'MESSAGE' : 'KEY ERROR'}, status=400) This is my unit test code about BiddingView so far, which obviously only works for decorator @patch('users.utils.requests') def test_kakao_message_success(self, mock_requests): class … -
Django: How does django-admin-sortable2 package code work?
I am using a package called "django-admin-sortable2" but I do not understand what I am coding. May someone explain? Here's what I used: https://django-admin-sortable2.readthedocs.io/en/latest/usage.html#sortable-many-to-many-relations-with-sortable-tabular-inlines Here's the GitHub repository: https://github.com/jrief/django-admin-sortable2 Here's the code example they used: models.py from django.db.import models class Button(models.Model): """A button""" name = models.CharField(max_length=64) button_text = models.CharField(max_length=64) class Panel(models.Model): """A Panel of Buttons - this represents a control panel.""" name = models.CharField(max_length=64) buttons = models.ManyToManyField(Button, through='PanelButtons') class PanelButtons(models.Model): """This is a junction table model that also stores the button order for a panel.""" panel = models.ForeignKey(Panel) button = models.ForeignKey(Button) button_order = models.PositiveIntegerField(default=0) class Meta: ordering = ('button_order',) admin.py from django.contrib import admin from adminsortable2.admin import SortableInlineAdminMixin from models import Panel class ButtonTabularInline(SortableInlineAdminMixin, admin.TabularInline): # We don't use the Button model but rather the juction model specified on Panel. model = Panel.buttons.through @admin.register(Panel) class PanelAdmin(admin.ModelAdmin) inlines = (ButtonTabularInline,) -
Why data is not saved from the form?
I can't understand why the data from the form is not stored in the database. My code : .views.py def create(request): error = '' if request.method == 'POST': form = ProductForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: error = 'Форма некоректна' form = ProductForm() data = { 'form': form, 'error': error } return render(request, 'create_product.html', data) .forms.py class ProductForm(ModelForm): class Meta: model = Product fields = ['title','start_date','end_date','quantity_lections','photo','description','small_description',"slug"] widgets = { 'title': TextInput(attrs={'class': 'form-control', 'placeholder': 'Назва курсу'}), "slug" : TextInput(attrs={'class': 'form-control'}) , 'small_description': Textarea(attrs={'class': 'form-control','placeholder': 'Наприклад,опишіть для кого цей курс'}), 'description': Textarea(attrs={'class': 'form-control', 'placeholder': 'Опис'}), 'start_date': DateTimeInput(attrs={'class': 'form-control',"type": "date"}), 'end_date': DateTimeInput(attrs={'class': 'form-control',"type": "date"}), 'quantity_lections': NumberInput(attrs={'class': 'form-control'}), 'photo' : FileInput(attrs={'class':'form-control'}) } When I press the submit button, I get in the console POST request with code 200. -
Django subclass model gives "duplicate key value violates unique constraint" on save
I have a class with many fields: class Parent(models.Model): id = models.AutoField(primary_key=True) ... many more fields and I create a subclass class Child(Parent): other_field = models.CharField(max_length=512, blank=True, null=True) date_featured = models.DateField() After I migrate and create a Child object in the admin I get duplicate key value violates unique constraint "parent_pkey" DETAIL: Key (id)=(5) already exists. I've seen some similar questions that suggest that you modify the database but I can't easily do that. Do I need to change the id of the subclass? -
get_tenant() missing 1 required positional argument: 'request'
I'm working on Django with multi tenants package and i have followed a tutorial to have only one login page : https://blog.learningdollars.com/2020/08/02/how-to-implement-django-tenant-schemas-with-a-fixed-url/ this is my code : from datetime import date from dateutil.relativedelta import relativedelta from django.core.exceptions import ObjectDoesNotExist from django_tenants.middleware.default import DefaultTenantMiddleware from django_tenants.utils import get_public_schema_name class RequestIDTenantMiddleware(DefaultTenantMiddleware): def get_tenant(self, model, hostname, request): try: public_schema = model.objects.get(schema_name=get_public_schema_name()) except ObjectDoesNotExist: public_schema = model.objects.create( domain_url=hostname, schema_name=get_public_schema_name(), tenant_name=get_public_schema_name().capitalize(), paid_until=date.today() + relativedelta(months=+1), on_trial=True) public_schema.save() x_request_id = request.META.get('HTTP_X_REQUEST_ID', public_schema.tenant_uuid) tenant_model = model.objects.get(tenant_uuid=x_request_id) print(tenant_model, public_schema) return tenant_model if not None else public_schema i'm getting as an error : TypeError at /client get_tenant() missing 1 required positional argument: 'request' -
Reference to global variable stays on the view even after it's not getting triggered
I want to display an error message to the user when an Exception is triggered. By default, the error_message should be False and when an Exception is triggered error_message should be updated with the exception message. When the exception is triggered my html page successfully displays the error message, but when I reload the page the error message is still displayed although the exception isn't being triggered anymore. By default it needs to stay False, but why does the reference to the global variable not get overridden on a page reload? error_message = False def home_page(request): if request.method == 'POST': try: #execute mySQl query db_error_message = False except Exception as e: db_error_message = e return HttpResponseRedirect("/hardware_milestone/") context = {'error_message ': error_message } return render(request, 'home_page.html', context}) -
Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7fb2bc14aa90>": "Post.created_by" must be a "User" instance
I'm trying to make a post as a logged user but when I try to do so, I get this error: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7fb2bc14aa90>": "Post.created_by" must be a "User" instance. I figured there's an issue when it comes to keeping the user logged in since I did get the token and all the data when I logged it in but that seems to disappear the moment I go to another view in the API. How can I fix it? These are the serializers: class UserLoginSerializer(serializers.ModelSerializer): """ User Login Serializer """ username = serializers.CharField( required=True, write_only=True, ) token = serializers.CharField( allow_blank=True, read_only=True ) password = serializers.CharField( required=True, write_only=True, style={'input_type': 'password'} ) class Meta(object): model = User fields = ['id','username', 'password', 'token'] def validate(self, data): username = data.get('username', None) password = data.get('password', None) if username and password: user = authenticate(request=self.context.get('request'), username=username, password=password) if not user: msg = 'Unable to log in with provided credentials.' raise serializers.ValidationError(msg, code='authorization') else: msg = "Must include username and password." raise serializers.ValidationError(msg, code='authorization') data['user'] = user return data class PostSerializer(serializers.ModelSerializer): """ Post Serializer """ replies = serializers.SerializerMethodField('get_replies') class Meta: model = Post fields = ['category','title','body','created_at','replies'] extra_kwargs = {'created_by': {'read_only':True}} def get_replies(self, obj): serializer = … -
Login and Logout views are they necessary? ( SimpleJwt+Django rest framework)
So according to many examples out there. some projects would actually build a Loggin view that uses the AccesToken and a Logout view that could use the Blacklist. while others would just use AccesToken,Refresh , Blacklist directly and handle the login/logout from the frontend(a consumer like React,...) with out the need to use Views.py i was wondering if one is better than the other, or is there any difference (performance wise, or security,...) Thanks -
Django Queryset: Only return entries where a specific field appears greater than N times
Let's say I have a model with a user foreignkey and a charfield. How can I filter a queryset so that only users with > 3 entries are returned in one line? So something like this (which obviously does not exist yet): Post.objects.filter(user__appears__gte=2) -
Django forms, form is always invalid
Yes, I did look at the other responses to similar questions. But I haven't found one that helps me, Ive looked at all the currently available solutions. I am trying to enter a name into a textbox, and then hit submit, allowing me to create a new list of items (the items are irrelevant). But when I hit the submit button nothing happens. After many print statements, Ive deduced that the reason why is because the form.is_valid() function is returning false if response.method == "POST": # returns a dictionary of information in the form form = CreateNewList(response.POST) print(form.errors) # if the form is valid, get the name attribute and create a new ToDoList with it if form.is_valid(): n = form.cleaned_data["name"] t = ToDoList(name=n) t.save() return HttpResponseRedirect("/%i" % t.id) else: form = CreateNewList() return render(response, "main/create.html", {"form": form}) After reading some posts I found online, the next step I took was printing out the errors using forms.errors This is what I got from that print out <ul class="errorlist"><li>check<ul class="errorlist"><li>This field is required.</li></ul></li></ul> At this point, I have no clue what check is or does. One persons response online said that it is part of some dictionary and I have to do … -
Django One to Many Loose Relationship
Backstory Data is being pulled from an accounting system that can have department, market, and client relationship data associated with it. The relationship data are all TEXT/CHAR fields. They are not integer columns. There are over 2 million rows. The problem The problem I've been running into is how to add the lines without relationship validation that could fail because the related table (like Market) is missing the value or has been changed (because we are looking far back in the past). The naming of the columns in the Django database (more detail below), and querying Django models with a join that don't have a relationship attribute on the class. models.py from typing import Optional from django.db import models class Line(models.Model): entry_number: int = models.IntegerField(db_index=True) posting_date: date = models.DateField() document_number: Optional[str] = models.CharField(max_length=150, null=True, default=None) description: Optional[str] = models.CharField(max_length=150, null=True, default=None) department: Optional[str] = models.CharField(max_length=150, null=True, default=None) market: Optional[str] = models.CharField(max_length=150, null=True, default=None) amount: Decimal = models.DecimalField(max_digits=18, decimal_places=2) client: Optional[str] = models.CharField(max_length=150, null=True, default=None) # This relationship works account = models.ForeignKey(Account, on_delete=models.DO_NOTHING, related_name='lines') class Department(models.Model): code: str = models.CharField(max_length=10, db_index=True, unique=True, primary_key=True) name: str = models.CharField(max_length=100, null=True) class Market(models.Model): code: str = models.CharField(max_length=10, db_index=True, unique=True, primary_key=True) name: str = models.CharField(max_length=100, … -
Django Form doesn't show the initial value
I don't know if i'm doing something wrong but even when i set a initial value in a django form, that value doesn't show in the form. class EditForm(forms.Form): title = forms.CharField() content = forms.CharField() def edit(request, name): initial_data = { 'title' : name.capitalize(), 'content' : util.get_entry(name) } if request.method == "POST": form = EditForm(request.POST, initial=initial_data) if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] util.save_entry(title, content) return HttpResponseRedirect(reverse('wiki:index')) return render(request, "encyclopedia/edit.html", { "name" : name.capitalize(), "content" : util.get_entry(name), "form" : NewTaskForm() }) I'm trying to show the name and the content of a markdown archive to edit that same file, the entire app is working fine (import and saving the file). The server doesn't show any error messages and the page loads with no problems. (If somenthing is wrong if the question i apologize, my english isn't one of the best) -
Stripe: No signatures found matching the expected signature for payload using Django
While calling a Stripe Web hook, I am getting this error: No signatures found matching the expected signature for payload I am following this article: https://stripe.com/docs/billing/subscriptions/checkout#provision-and-monitor And I have following code: @csrf_exempt def saaswebhookview(request): try: stripe.api_key = settings.STRIPE_SECRET_KEY webhook_secret = 'stripe_key' request_data = request.POST if webhook_secret: try: signature = request.headers.get('stripe-signature') # signature = request.META['stripe-signature'] event = stripe.Webhook.construct_event( payload=request.POST, sig_header=signature, secret=webhook_secret) data = event['data'] except Exception as e: print(str(e)) return JsonResponse({'status': 'error', 'error': str(e)}) event_type = event['type'] else: data = request_data['data'] event_type = request_data['type'] data_object = data['object'] if event_type == 'checkout.session.completed': print(data) elif event_type == 'invoice.paid': print(data) elif event_type == 'invoice.payment_failed': print(data) else: print('Unhandled event type {}'.format(event_type)) return JsonResponse({'status': 'success'}, safe=False) except Exception as e: return JsonResponse({'status': 'success', 'error': str(e)}, safe=False) But strangely this throws me the error don't know why? -
default value not show in django formset
i'm trying to build an app which contains django inline formset , but default values only show for the first form!? this is my model class Main(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) A= models.ManyToManyField(Item,through='Child') B = models.IntegerField() class Child(models.Model): main = models.ForeignKey(Main,on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE) quantity = models.IntegerField(default=1) my views.py class CreateMainInlineFormset(LoginRequiredMixin,SuccessMessageMixin,CreateView): model = Main form_class = MainForm template_name = 'main/create.html' def get_context_data(self, *args,**kwargs): data = super().get_context_data(*args,**kwargs) if self.request.POST: data['items'] = ChildInlineFormSet(self.request.POST) data['items'].full_clean() else: data['items'] = ChildInlineFormSet() return data def form_valid(self, form): context = self.get_context_data() items = context['items'] with transaction.atomic(): self.object = form.save(commit=False) form.instance.admin = self.request.user if items.is_valid() and form.is_valid() and items.cleaned_data!={}: items.instance = self.object form.save(commit=True) items.save() else: return render(self.request,self.template_name,context) return super().form_valid(form) def get_success_url(self): return reverse_lazy('maininfo:list-item') my forms.py class ParentForm(forms.ModelForm): class Meta: model = Main fields = [ '__all__' ] class ChildForm(forms.ModelForm): class Meta: model = Child fields = [ '__all__' ] ItemInlineFormSet = inlineformset_factory( Main,Child,form=ChildForm,fields=( 'item','quantity'), extra=1 ) i have to display quantity default value for all of the forms , but it only display for the first form , the rest will be null -
tailwind sheet not showing up django
I just can't connect it! I used the CDN and it worked but I need it to have files offline as well so, I need the files natively as well. HTML and file structure below! Thanks :) My HTML : {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>#title</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{%static "/css/style.min.css"%}"> </head> <body class= "bg-red-800"> <h1 class = "something">This can be edited using tailwind</h1> {% comment %} {% include "schedule/navbar.html" %} {% endcomment %} {% block content %} {% endblock %} </body> </html> File structure: -
Removing a field from a django model form breaks the formatting in the HTML
Removing a field from my forms.py django form removes formatting although form works fine. If I remove "useremail" (as this is now paired up with the standard django User model email), all of the formatting / placeholders etc is removed from all of the fields in the HTML. This happens if I remove any of the 4 fields. All of the forms work, although it loses any control over attributes and styling. Picture 1 shows the html with everything below (this works fine). If I remove "useremail" from the forms.py, the formatting breaks as seen in picture 2. No error messages flag in the console forms.py class SafezoneForm(forms.ModelForm, admin.ModelAdmin): name = forms.CharField(label='Safezone name',widget=forms.TextInput (attrs={'id': 'name', 'label': 'Name of Safezone', 'class': 'form-inputs'})) useremail = forms.CharField(label='Your Email', widget=forms.EmailInput (attrs={'id': 'useremail','class': 'form-inputs',"placeholder": "mike@xyz.com"})) latitudecentre = forms.FloatField(label='Marker Latitude',widget=forms.TextInput (attrs={'id': 'latitudecentre','class': 'form-inputs', 'readonly': True})) longitudecentre = forms.FloatField(label='Marker Longitude',widget=forms.TextInput (attrs={'id': 'longitudecentre','class': 'form-inputs', 'readonly': True})) class Meta: model = Safezone models.py class Safezone(models.Model): userid = models.OneToOneField(User, on_delete=models.CASCADE, null=True) useremail = models.EmailField(User, null=True) name = models.CharField(max_length=100, null=True) latitudecentre = models.FloatField(null=True) longitudecentre = models.FloatField(null=True) latcorner1 = models.FloatField(null=True) def save(self, *args, **kwargs): self.latcorner1 = self.latitudecentre + 0.1 super(Safezone, self).save(*args, **kwargs) def __str__(self): return str(self.userid) or '' Views.py def collapsecard(request): if … -
Django Querysets: Ordering posts by number of similar tags
Let's say I have a Django model for : Post - Representing a blog post Tag - Representing a canonical Tag. Let's pretend it's a hashtag. PostTag - A foreign key intermediary between Posts and Tags. Now let's say I have 5 posts with these tags: #food #story #recepie #gardening #entree #food #story #recepie #ham # sandwich #food #story #flowers #fish #sushi #food #story #computer #keyboard #mouse #food #coffee #vitamins #basil #citrus -- Given Post 1 with it's 5 tags, how can I get N number of other posts with the most similar tags? Posts.objects.filter(publish_at__gte=somedatetime).order_by("similarity") -
Run Django in production or development mode and let variables depend on it
I'm working on a Django project and in one of my functions I'm redirecting the user to a redirect url which is different in production and development. When the project is running in production, it's starting up the server with the wsgi.py file and gunicorn. When I'm developing I start up the server with python manage.py runserver. So I figured I can just initialise environment variable 'DEVELOPMENT_MODE'='FALSE' and then evaluate os.environ.get('DEVELOPMENT_MODE') in the py file where I have the redirect url, since this environment variable will not be initialised with python manage.py runserver. This doesn't seem to be working though and I'm looking for a solution. This is my first project in Django. -
Django charfield problem not returning value of text
`from django.db import models class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def str(self): """Return a string representation of the model""" return self.text` So the above code contains variable text which stores the 'Topic' name but as i enter the topic name in django site admin it never shows the text rather than it stores and display "object(1) is successfully stored" -
Django template context not working with date template tag
I'm passing the date as an entire string as below: def template_test(request): context = { 'day': '2021-04-19T03:00:00Z', } return render(request, 'date_test.html', context=context) date_test.html {% extends 'base.html' %} {% block content %} <p>Here is the day {{ day|date:"l, j M y" }}</p> {% endblock %} Does anyone know why when I add a date template tag on my day variable it doesn't work? If I remove it, the day variable is showing normally but with filter not. -
How to increment a column by 1 for each time a link is clicked on a webpage (Django)?
Background: The website displays a list of products that all have a link to an external site. I would like to create a counter that adds 1 to the column "views" for each time the products link is clicked. This is to see which product has been clicked the most. I would appreciate any help? The "views" column stores the number of times the link is clicked. models.py class T_shirt(models.Model): Images = models.ImageField() Titles = models.CharField(max_length=250, primary_key=True) Prices = models.CharField(max_length=250) Link = models.CharField(max_length=250) Website = models.CharField(max_length=250) Brand = models.CharField(max_length=250) views = models.IntegerField(default=0) HTML <ul class="products"> {% for v in owner_obj %} <div class="container"> <a href={{ v.Link }} target="_blank" rel="noopener noreferrer"> <img src={{ v.Images }} width="150" height="150"> </a> <figcaption> {{ v.Titles }} </figcaption> <figcaption> <b>{{ v.Prices }} </b></figcaption> </div> {% endfor %} </ul> -
Django Rest Framework sending email but template doesnt load CSS
I am sending an email from Django Rest using django.core.mail module. Views.py from django.core.mail import send_mail from django.template.loader import render_to_string from django.utils.html import strip_tags ... ## Send the email somewhere in the viewset html_mail = render_to_string('emails/invitation.html', {'email': email, 'url': url, 'invitation_code': invitation_code}) mail_template = strip_tags(html_mail) send_mail( 'You are invited!', mail_template, [sender_mail], [email], fail_silently=False, ) return Response({'message': 'Invitation email sent to ' + email},200) I have template path in the settings, TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], And on the template I have the regular HTML template with a bunch of CSS code. Example Email Template: <!DOCTYPE html> <html lang="en" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"> <head> <meta charset="utf-8"> <meta name="x-apple-disable-message-reformatting"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="format-detection" content="telephone=no, date=no, address=no, email=no"> <!--[if mso]> <xml><o:OfficeDocumentSettings><o:PixelsPerInch>96</o:PixelsPerInch></o:OfficeDocumentSettings></xml> <style> td,th,div,p,a,h1,h2,h3,h4,h5,h6 {font-family: "Segoe UI", sans-serif; mso-line-height-rule: exactly;} </style> <![endif]--> <title>Default email title</title> <link href="https://fonts.googleapis.com/css?family=Montserrat:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,200;1,300;1,400;1,500;1,600;1,700" rel="stylesheet" media="screen"> <style> .hover-underline:hover { text-decoration: underline !important; } @keyframes spin { to { transform: rotate(360deg); } } @keyframes ping { 75%, 100% { transform: scale(2); opacity: 0; } } @keyframes pulse { 50% { opacity: .5; } } @keyframes bounce { 0%, 100% { transform: translateY(-25%); animation-timing-function: cubic-bezier(0.8, 0, 1, 1); } 50% { transform: none; animation-timing-function: … -
Docker: a web service built but failed to execute
I`m trying to build a Django web service with docker. The docker file is ENV DockerHOME=/home/xs1_glaith/cafegard RUN mkdir -p $DockerHOME WORKDIR $DockerHOME ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 the docker-compose file is like this version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgress - POSTGRES_USER=postgress - POSTGRES_PASSWORD=postgress web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/home/xs1_glaith/cafegard ports: - "8000:8000" depends_on: - db COPY . $DockerHOME RUN pip install --upgrade pip RUN pip install -r $DockerHOME/requirements.txt EXPOSE 8000 CMD python manage.py runserver finally, the result is Starting cafegard_db_1 ... done Creating cafegard_web_run ... done Error response from daemon: OCI runtime create failed: container_linux.go:367: starting container process caused: exec: ".": executable file not found in $PATH: unknown ERROR: 1 I dont really understand whats the problem or what`s make the problem!!!