Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create Django formset from jquery dynamically form?
After user fill a basic form, the data will be showed in table, dynamically created via jquery. index.html <form> <div class="row"> <div class="col-md-6 mb-3"> <label for="sourceip">Source IP:<span> *</span></label> <input type="text" class="form-control" id="sourceip" placeholder="_._._._ , _._._._ , _._._._" value="" > <span class="error_form" id="sourceip_error_message"></span> </div> <div class="col-md-6 mb-3"> <label for="destip">Destination IP:<span> *</span></label> <input type="text" class="form-control" id="destip" placeholder="_._._._ , _._._._ , _._._._" value="" > <span class="error_form" id="destip_error_message"></span> </div> </div> <div class="mb-3"> <label for="service">Service:<span> *</span></label> <div class="input-group"> <input type="text" class="form-control" id="service" placeholder="" > <span class="error_form" id="service_error_message"></span> </div> </div> <div class="mb-3"> <label for="comment">Comment: </label> <textarea type="text" class="form-control" id="comment" placeholder="Add comment"> </textarea> </div> <hr class="mb-4"> <input type="button" class="btn btn-primary btn-lg btn-block add" value="Add rule"> </form> <div id="tabulka" class="table col-md-10"> <form method="POST" action="#" enctype="multipart/form-data"> {% csrf_token %} <!--{{ formset.management_form }}--> <table > <thead class="thead-dark"> <th scope="col">Source IP</th> <th scope="col">Destination IP</th> <th scope="col">Service</th> <th scope="col">Comment</th> <th scope="col" colspan="2">Action</th> </thead> <tbody id="tbody"> </tbody> </table> <input type="submit" value="insert record"> </form> </div> script.js $(".add").click(function () { var SourceIP = CheckIPAdresses($("#sourceip").val()); var DestIP = CheckIPAdresses($("#destip").val()); var Service = CheckService($("#service").val()); var Comment = $("#comment").val(); for (sadd in SourceIP ){ for (dadd in DestIP){ for (srv in Service){ var markup = "<tr class='table-row' > <td class='SourceIP'> <input name='sip' type='text' class='sip' readonly value='"+SourceIP[sadd] + "'> … -
How to change the default error messages displayed by Django forms
I have created a form in Django which has a charfield with max_length=255 as follows: task = models.CharField(max_length= 255) Now I want to let the user know how many characters he has typed if he exceeds the 255 characters limit, so I did the following if form.is_valid(): #some code else: messages.info(request,(form.errors.get("item").as_text())) now consider two scenarios (1) I am leaving the field blank (2) type 445 characters in the form field and submit then by default I am getting the following error messages: Scenario 1: * This field is required. Scenario 2: * Ensure this value has at most 255 characters (it has 445). but instead, I want to change these messages to: Scenario 1: No task added! Scenario 2: Error: maximum length limit is 255 characters (it has 445). So I tried the following: class ListForm(ModelForm): class Meta: model = ListModel fields = ["task", "status"] error_messages = { 'task': { "required": ("No task added!") 'max_length': ("Error: maximum length limit is 255 characters"), }, } Now the messages have been changed to: Scenario 1: * No task added! Scenario 2: * Error: maximum length limit is 255 characters. My Problem: I don't want the * which is being displayed in front … -
raise Http404 returns 500 page instead of 404 custom page
In my app urls.py I have: handler404 = 'app.views.page_not_found' In my views.py I have: def page_not_found(request, exception): return render(request, '404.html', status=404) Entering invalid url will display the custom 404 page as should be. But when I raise 404, in views.py of some module of the Django app, it return 500 page instead of 404 page (I use raise Http404). Do I need to add something in the urls.py of that module? Why it does not show the 404 page? -
DoesNotExist at /adminpanel/ Inspector matching query does not exist
I am trying to fetch some data from the database by satisfying a particular field's value true. my models.py: class Inspector(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, related_name='inspector_releted_user') name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) nid = models.IntegerField(blank=False, unique=True) rank = models.CharField(max_length=20, blank=False, null=True) inspector_varified = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.name Now I try to fetch only those data which case inspector_varified 's value is True. my views.py: def adminpanel(request): adminpanel_dict = { 'inspector' : Inspector.objects.get(inspector_varified=True) } return render(request, 'app/adminpanel.html', adminpanel_dict) but it shows error like: Inspector matching query does not exist. How can I fix it? -
Reason for Serializer not working in Django Project
I am working on a Django Project and added a Theme Selection Functionality. The user can select the theme either Light or Dark and it reflects in the backend by the CSS file under the setting.value. I create a mode app and it has the current attributes: class Setting(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="mode",null=True,blank=True) name = models.CharField(max_length=200, null=True) value = models.CharField(max_length=200) def __str__(self): return self.name In the views the user setting is not reflecting properly as it is always showing User don't have a setting., however the updateTheme is working perfectly fine. This is the first time I configure rest_framework to my app. from .serializers import UserSerailizer def userSettings(request): user, created = User.objects.get_or_create(id=1) setting = getattr(user, 'setting', None) if setting: seralizer = UserSerailizer(setting, many=False) return JsonResponse(seralizer.data, safe=False) else: return JsonResponse({'message': "User don't have a setting."}, safe=False) def updateTheme(request): data = json.loads(request.body) theme = data['theme'] user = request.user setting = Setting.objects.update_or_create( user=user, defaults={'value': theme}, name='theme') print('Request:', theme) return JsonResponse('Updated..', safe=False) serializer.py from rest_framework import serializers from .models import * class UserSerailizer(serializers.ModelSerializer): class Meta: model = Setting fields = '__all__' Everytime a User logs in in the console I am receiving the error Data: {message: "User don't have a setting."} In the … -
django - adding new Inline form using smart-selects nothing happens
I have a code below. class Evaluation(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) class EvaluationDisability(models.Model): disability = models.ForeignKey(Disability, on_delete=models.CASCADE) disability_details = ChainedManyToManyField( DisabiltiyDetail, horizontal=True, chained_field="disability", chained_model_field="disability") # evaluation = models.ManyToManyField(Evaluation,blank=False) evaluation = models.ForeignKey(Evaluation, on_delete=models.CASCADE) class EvaluationDisabilityForm(forms.ModelForm): model = EvaluationDisability class EvaluationDisabilityInline(admin.TabularInline): model = EvaluationDisability form = EvaluationDisabilityForm extra = 1 # autocomplete_fields = ['disability_details'] @admin.register(Evaluation) class EvaluationAdmin(admin.ModelAdmin): model = Evaluation inlines = [EvaluationDisabilityInline] right there is says extra=1 So on the admin page the smart-selects is workin fine just for only 1 row. But adding new row.. smart-selects not working anymore. Same thing if i change the extra to any number. for example extra=5. smart-selects works for the first 5 rows but adding a new one will do nothing. Please help been looking for the resolution on this for weeks now -
Django - How get IP of request in a custom receiver?
I have following code: @receiver(user_logged_in) def user_logged_in_callback(sender, request, user, **kwargs): ip = request.META.get('REMOTE_ADDR') AuditEntry.objects.create(action='User logged in', ip=ip, username=user.username) It works great. In views.py I have a custom receiver: @receiver(pre_save, sender=User) def user_updated(sender, **kwargs): user = kwargs.get('instance', None) ip = request.META['REMOTE_ADDR'] if user: new_password = user.password try: old_password = User.objects.get(pk=user.pk).password except User.DoesNotExist: old_password = None if new_password != old_password: AuditEntry.objects.create(action='Password has changed', ip="127.0.0.1", username=user.username) For sure it falls with "no request found" error. I can't figure out how to extract IP. Thank you. -
Django migration error when database has custom views
Django 3.1. app folder : stocks project folder with settings inside: main I have this model: class Bar(models.Model): stock = models.CharField(max_length=10) timestamp = models.DateTimeField() date = models.DateField() time = models.TimeField() open = models.DecimalField(max_digits=6, decimal_places=2) high = models.DecimalField(max_digits=6, decimal_places=2) low = models.DecimalField(max_digits=6, decimal_places=2) close = models.DecimalField(max_digits=6, decimal_places=2) is_regular = models.BooleanField() change = models.DecimalField(max_digits=10, decimal_places=4) In the SQLite database I have created view daily_bottoms from that model using SQliteStudio. Now I am trying to migrate because added another field. makemigrations works fine, but when trying to migrate I get an error: django.db.utils.OperationalError: error in view daily_bottoms: no such table: main.stocks_bar If I delete the view then it will migrate , but I would like to avoid that every time. How to make it work? -
Django admin 'pk' attribute error in main site
I am using the default admin site with the following config: urls.py: urlpatterns = [ path('admin/', admin.site.urls) ] settings.py: INSTALLED_APPS = [ 'django.contrib.admin' ] admin.py admin.site.register(Student) I removed everything unrelated to admin. The error AttributeError: 'NoneType' object has no attribute 'pk' occurs ONLY when accessing localhost/admin. In other words, accessing the database directly like localhost/admin/school/student doesn't throw an exception. Full Traceback: Traceback (most recent call last): File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 202, in _get_response response = response.render() File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 938, in render bit = … -
Django How to convert image to base64 then make a post request with the result
I'm trying to make a form with an image upload field then I convert this image to base64 and make a post request to an API with the base64 in the body my forms.py: class FridgeForm(forms.ModelForm): class Meta(forms.ModelForm): model = Fridge fields = [ 'name', 'date', 'picture' ] widgets = { 'date': forms.DateTimeInput } I tried to do it with jquery using val() but I get the image path string not the image $(document).on('submit', function(e){ e.preventDefault(); }) function canvasBase64(image) { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); canvas.width = image.width; canvas.height = image.hight; ctx.drawImage(image, 0, 0) return canvas.toDataURL('image/jpeg') } $("button.encode").on("click", function(){ const image = $("input[name=picture]").val() console.log(typeof image) console.log(image) canvasBase64(image, function(base64) { console.log('RESULT: ', base64) fetch(url, { method: 'POST', headers: { "X-CSRFToken": csrftoken, }, body: (base64) }) .then(response => response.json()) .then(data => { console.log('data: ', data) }) }) }) -
Django CMS in Django
I am building a django app that would allow users to create html content (to be used as an email template), but keep getting TemplateSyntaxError. I am trying to use the django-cms plugins in my own view and templates any ideas. {% extends 'admin/merchant/base.html' %} {% load cache %} {% load cms_tags %} {% block extra_head %} {% placeholder "css" %} {% endblock extra_head %} {% block content %} <body> {% cms_toolbar %} {% placeholder "content" or %} Nothing is coming through... {% endplaceholder %} </body> {% endblock content %} but i get this error: Template error: In template /home/joel/Projects/Vendora Deploy/src/templates/admin/merchant/newsletter/create-page.html, error at line 15 Invalid block tag on line 15: 'endblock'. Did you forget to register or load this tag? 5 : {% block extra_head %} 6 : {% placeholder "css" %} 7 : {% endblock extra_head %} 8 : 9 : {% block content %} 10 : <body> 11 : {% cms_toolbar %} 12 : 13 : {% placeholder "content" or %} Nothing is coming through... {% endplaceholder %} 14 : </body> 15 : {% endblock content %} 16 : 17 : 18 : ``` [1]:[Traceback Image][1] https://i.stack.imgur.com/PkHi9.png -
How do I write a rest framework serializer to create an instance of a model containing both foreign key relations and generic relations?
I'm trying to create instances of a model using a POST method on django rest framework. I need a serializer method which can handle the logic behind this. In my models I have two instances of a foreign key and one instance of a generic relation foreign key. Here are my models: class UserModel(models.Model): MEMBERSHIP_TYPE = [ ('NM', 'NORMAL'), ('PT', 'PLATA'), ('OR', 'ORO'), ('PL', 'PLATINO'), ] id = models.AutoField(primary_key=True) username = models.CharField(max_length=100) photo = models.ImageField(upload_to='images/', blank=True) address = models.TextField() client_type = models.CharField(max_length=2, choices=MEMBERSHIP_TYPE, default= 'NM') def __str__(self): return self.username class ArticleModel(models.Model): id = models.AutoField(primary_key=True) code = models.IntegerField() description = models.TextField() def __str__(self): return self.code class OrderModel(models.Model): id = models.AutoField(primary_key=True) client = models.ForeignKey('UserModel', on_delete=models.CASCADE) gen_time = models.DateTimeField(auto_now_add=True) gen_supplied = models.DateTimeField() urgent = models.BooleanField() order_to = GenericForeignKey() article = models.ForeignKey('ArticleModel', on_delete=models.CASCADE) quantity= models.IntegerField() object_id = models.BigIntegerField(default=None, null=True) content_type = models.ForeignKey( ContentType, default=None, null=True, on_delete=models.SET_NULL) class WarehouseModel(models.Model): id = models.AutoField(primary_key=True) warehouse_num = models.IntegerField() order_rel = GenericRelation(OrderModel) class StoreModel(models.Model): id = models.AutoField(primary_key=True) reference = models.IntegerField() store_num = models.IntegerField() order_rel = GenericRelation(OrderModel) class BusinessModel(models.Model): id = models.AutoField(primary_key=True) reference = models.IntegerField() store_num = models.IntegerField() order_rel = GenericRelation(OrderModel) class DetailModel(models.Model): id = models.AutoField(primary_key=True) detail = models.TextField() order = models.ForeignKey('OrderModel', on_delete=models.CASCADE) and here's my serializer so far: class … -
See how many orders he has on his profile page. Django
When I enter my user profile page, I want it to see the total number of orders until today. i tried aggregate and annonate but it's not work. I hope so i use filter method but i don't know how to do it. Orders count = adet in model I added ""if siparis.bayi_id == user.id"" so that the user entering can take action on his orders. Temp Html {% for siparis in siparis %} {% if siparis.bayi_id == user.id %} <strong>{{ a }}</strong><br><small>Siparişler Toplamı</small> {% endif %} {% endfor %} Model Siparis means order class Siparis(models.Model): bayi = models.ForeignKey('auth.User', verbose_name='bayi', on_delete=models.CASCADE, related_name='bayi',limit_choices_to={'groups__name': "BayiGrubu"}) urun = models.ForeignKey(Urun, on_delete=models.CASCADE) adet = models.IntegerField() tarih = models.DateTimeField() status = models.BooleanField() @property def miktar(self): return (self.adet * self.urun.fiyat) @property def fiyat(self): return self.urun.fiyat class Meta: verbose_name = 'Bayi Sipariş' verbose_name_plural = 'Bayi Siparişleri' views def bayi_bayidetay(request): siparis = Siparis.objects.all() urunler = Urun.objects.all() bayiler = bayi_bilgi.objects.all() a = Siparis.objects.aggregate(Sum("adet")) return render(request,'bayi/bayi_detay.html',{'bayiler':bayiler,'siparis':siparis,'urunler':urunler, 'a': a}) Thank you -
how to trigger AWS Lambda function with Django framework?
I need to create a Button with Django Framework and connect to trigger lambda function (aws), click to button to should trigger the function. Also, another page to upload files to S3 Bucket with django from local. Should I work on REST API or there is a way around this. how to get started on this or execute the idea? also helpful if you could share resources on this. -
CkEditor image works in localhost but in production it doesn't preview image and save image in Django framework
Here is my settings.py file. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') MEDIA_DIR = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' MEDIA_ROOT = MEDIA_DIR CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_CONFIGS = { 'default': { 'extraPlugins': 'codesnippet', 'toolbar': 'full', 'height': 300, 'width': '100%', 'contentsCss': 'img {max-width: 100%;height: auto! important;}', }, } I have kept CKEditor folder under the static folder. Uploading images using RichTextUploadingField works correctly in localhost. In Production server (cPanel) after DEBUG = False it is not previewing any images clicking "Send it to the Server" and not saving the images. Please help regarding the issue. -
Field 'id' expected a number but got <QuerySet [<Example: 9NjKaWHB3q6SVSq>]>
I wish you a good years, I got an issue. I'd like to get resa_exemple == exemple But I got an issue with this Field 'id' expected a number but got <QuerySet [<Example: 9NjKaWHB3q6SVSq>]> I don't really understand why? class RerservationOrder(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) exemple = models.ManyToManyField('Example',blank=True, related_name='reservation_order_exemple') ... class Reservation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) resa_order = models.ManyToManyField('RerservationOrder',blank=True, related_name='resa_order_reservation') resa_exemple = models.ManyToManyField('Example',blank=True, related_name='resa_order_example') def AddResaOrder(request, slug, pk): current_reservation = get_object_or_404(Reservation, slug=slug) cuisine = get_object_or_404(Cuisine, id=pk) resa = current_reservation.resa_exemple.all() if request.method == "POST": #this work create_resa_order = current_reservation.resa_order.create(user=request.user, ...) #this does not work create_resa_order.exemple.add(resa) #this work current_reservation.resa_order.add(create_resa_order) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) -
Handling text files Heroku's ephemeral file-system to upgrade Python
My Python runtime for one of my first Django projects which I am working on that I am deploying to Heroku is out of date. It’s Python version 3.6.7. My build log tells me I should be using a more recent version - - v3.6.12. When I Google, ‘how to upgrade python heroku’, the first search result is the official Heroku doc which identifies supported run times. The doc explains to view your current run time, you can use: $ python --version or in the project root use $ cat runtime.txt and to select a run time, you can change the contents of runtime.txt. I found the file and I can view its contents with cat. It’s Python v3.6.7 for sure, which is out of date and needs to be changed. The two problems I have encountered are: Viewing the file is easy. What I can’t figure out is how to open/edit runtime.txt. My first instinct is to try CLI interface text editors such as vim, vi, pico, nano, all of which are not installed. My question is: How do I edit text files for my Django project on Heroku? Even once I find that out, my next problem is … -
How can I dynamically define forms.IntegerField's min_value parameter?
I am working with Django and its Forms classes. I have created a Form with a single forms.IntegerField and I want to define its min_value parameter dynamically: class BiddingForm(forms.Form): bidding_form = forms.IntegerField(min_value=1, help_text="€", label="Bid") Right now, it is statically set to 1. I have tried to overwrite the __init__() function and pass in a min_value there. But since bidding_form is a class variable, I cannot use the resulting instance variable min_value on it: class BiddingForm(forms.Form): min_value = 1 def __init__(self, min_value): super().__init__() self.min_value = min_value bidding_form = forms.IntegerField(min_value=min_value, help_text="€", label="Bid") As of my understanding, above class creates an instance variable min_value inside of __init__() which just shadows the class variable min_value and it ultimately results in min_value being 1 in the bidding_form's declaration. Since I have little understanding of Python and Django, I have not yet found a solution to this. So, how can I dynamically define forms.IntegerField's min_value parameter? -
Explanation on Django's request processing - Why does it select one urlpattern from another
So I am doing an free online course that involves Django and have run into something that is rather confusing regarding how Django processes requests. My Django application has a single module and within this module I have essentially two pages that I am generating both of which inherit from a layout template. There is an index page (which contains links to individual entries) and an entry page which displays the content of each individual entry. There are two ways to get to an entry page. You could either directly click on the link that is present on the index page or you could type in the search bar that is present on index page. If the name matches the entry in the search bar it will take you to that entry page. Each method of reaching an entry page has its own url pattern in the urls.py file and each one has its own route function in the views.py file. What was happening was that regardless of what was typed into the search bar, it would only use the route that was meant for directly clicking on the entry link from the index page rather than the route that … -
Could not setup django-oauth-toolkit authentication
I'm going to restrict my working rest_framework.views.APIView inherited class, to be visible only by authenticated users. I made these modifications: Added authentication_classes and permission_classes to my class: class TestView(APIView): authentication_classes = (OAuth2Authentication,) permission_classes = (IsAuthenticated,) return Response("Hey there...") Got an access_token from django-oauth-toolkit: curl -XPOST "http://172.18.0.1:8000/oauth2/token/" \ -d 'grant_type=client_credentials&client_id=MY-CLIENT-ID&client_secret=MY-CLIENT-SECRET' {"access_token": "Haje1ZTrc7VH4rRkTbJCIkX5u83Tm6", "expires_in": 36000, "token_type": "Bearer", "scope": "read write groups"} Tried requesting the view without setting the access_token: curl -XGET "http://172.18.0.1:8000/api/v1/test/" {"detail":"Authentication credentials were not provided."} Tried a new request with the access_token: {"detail":"You do not have permission to perform this action."} Should I do anything more to enable access_token authentication? Note: I have installed these libraries in the environment: Django==2.2.17 djangorestframework==3.12.2 django-oauth-toolkit==1.3.3 -
Error in the Syntax of Django urls.py file
in my website urls.py file for the file named "pollsapp"(name of my project) my code is from django.contrib import admin from django.urls import path , include urlpatterns = [ path('admin/', admin.site.urls), path('',include('pollsapp.urls')), ] also my website urls.py code for the file named "appy" ( which is my name of the web application) from django.urls import path from . import views urlpatterns = [ path('',views.home, name = 'home') ] and the error I am getting in both the urls terminal is : File "C:\Users\HP User\djangocode\pollsapp\pollsapp\urls.py", line 21 path('admin/', admin.site.urls), ^ SyntaxError: invalid syntax -
Block tags not appearing in django html template
I might have a bit complicated case but here it is, I have this base.html file which not only contains the tags, {% block title %}{% endblock %} But also some other tags for my navbar such as, {% block home %}{% endblock %}{% block profile %}{% endblock %}where I implement my active class. My navbar is being used as a separate html file which I am rendering using the include tag. The problem is, whenever I extend my base.html file, and render another html template, the title block works fine, but the ones in the navbar don't. Here is how I render it in my home.html {% extends 'base.html' %} {% load static %} {% block title %}Home{% endblock %} {% block home %}active{% endblock %} {# this tag doesn't work #} -
i am using five anchor tag but only first four working
i am working on a django project where i have use 5 anchor tag first 4 anchor tag working fine but the 5th one is not even behaving like a link ,my cursor not changing to pointer <div class="nav-bar"> <a href=""> home </a> <a href=""> about </a> <a href=""> contact </a> <a href=""> message </a> <a href=""> post </a> </div> -
Docker "is not a valid port number or address:port pair."
I am new in docker. I want to run my django app on port 9000. After command docker-compose up I am getting this message Creating motion_full_version_backend_1 ... done Attaching to motion_full_version_backend_1 backend_1 | Unknown command: 'makemigrations\r'. Did you mean makemigrations? backend_1 | Type 'manage.py help' for usage. backend_1 | Unknown command: 'migrate\r'. Did you mean migrate? backend_1 | Type 'manage.py help' for usage. " is not a valid port number or address:port pair.* My Dockerfile : FROM continuumio/miniconda3:latest ENV LANG=C.UTF-8 LC_ALL=C.UTF-8 RUN apt-get update && apt-get upgrade -y && apt-get install -qqy \ wget \ bzip2 \ graphviz RUN mkdir -p /backend COPY ./backend/requirements.yml /backend/requirements.yml # Create environment RUN /opt/conda/bin/conda env create -f /backend/requirements.yml # Add env path to environment ENV PATH /opt/conda/envs/backend/bin:$PATH # Activate interpreter RUN echo "source activate backend" >~/.bashrc # Create a scripts folder RUN mkdir -p /scripts COPY ./scripts /scripts RUN chmod +x ./scripts* COPY ./backend /backend WORKDIR /backend I am using script to run it python manage.py makemigrations python manage.py migrate python manage.py runserver 0.0.0.0:9000 my docker-compose.yml looks like this version: '3' services: backend: image: backend:latest restart: always env_file: - ./envs/dev.env command: 'sh /scripts/dev.sh' ports: - "9000:9000" Any Ideas what I am doing wrong? -
How to combine jwilder-nginx + django?
Honestly, I don't know nothing about nginx configuration and terms like "reverse proxy". I want to run my django project locally only, this is my actual docker-compose file configuration: version: "3" volumes: local_postgres_data: {} local_postgres_data_backups: {} services: nginx: image: nginx:alpine container_name: nz01 ports: - "8000:8000" volumes: - ./src:/src - ./config/nginx:/etc/nginx/conf.d depends_on: - web networks: - djangonetwork web: build: context: . dockerfile: compose/django/Dockerfile container_name: dz01 depends_on: - db volumes: - ./src:/src expose: - "8000" links: - redis env_file: - ./.envs/.django networks: - djangonetwork db: build: context: . dockerfile: compose/postgres/Dockerfile container_name: pz01 env_file: - ./.envs/.postgres volumes: - local_postgres_data:/var/lib/postgresql/data - local_postgres_data_backups:/backups networks: - djangonetwork redis: image: redis:alpine container_name: rz01 ports: - "6379:6379" networks: - djangonetwork networks: djangonetwork: driver: bridge and my nginx config file: client_max_body_size 10M; upstream web { ip_hash; server web:8000; } server { location /static/ { autoindex on; alias /src/static/; } location /media/ { autoindex on; alias /src/media/; } location / { proxy_pass http://web/; } listen 8000; server_name localhost; } I have read that Kubernetes Ingress service can be recreated for docker-compose with jwilder-nginx image, so you can have https certificate and use a url instead of host machine ip to access your django service, but I don't know how to …