Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
show reply button not working fine for comments in django
show Reply button should be specific for different comments ... when i press show reply button it open different replies which dosen't which doesn't belong to that comment views.py from django.shortcuts import render, HttpResponse, redirect,reverse from fitness.models import Post, BlogComment from django.contrib.auth.models import User from fitness.templatetags import extras # Create your views here. def fitness(request): everypost=Post.objects.all() context={"everypost":everypost} return render(request, "fitness/fit.html", context) def blogfit(request, slug): post=Post.objects.filter(slug=slug).first() comments= BlogComment.objects.filter(post=post, parent=None) replies= BlogComment.objects.filter(post=post).exclude(parent=None) replyDict={} for reply in replies: if reply.parent.sno not in replyDict.keys(): replyDict[reply.parent.sno]=[reply] else: replyDict[reply.parent.sno].append(reply) context={"post":post, 'comments': comments, 'user': request.user, 'replyDict': replyDict} return render(request, "fitness/blogfit.html", context) def postComment(request): if request.method == "POST": comment=request.POST.get('comment') user=request.user postSno =request.POST.get('postSno') post= Post.objects.get(sno=postSno) parentSno= request.POST.get('parentSno') if parentSno=="": comment=BlogComment(comment= comment, user=user, post=post) comment.save() else: parent= BlogComment.objects.get(sno=parentSno) comment=BlogComment(comment= comment, user=user, post=post , parent=parent) comment.save() return HttpResponse(reverse('fitness:fitness')) Models.py from django.db import models from ckeditor.fields import RichTextField from django.contrib.auth.models import User from django.utils.timezone import now # Create your models here. class Post(models.Model): sno=models.AutoField(primary_key=True) title=models.CharField(max_length=255) author=models.CharField(max_length=14) slug=models.CharField(max_length=130) timeStamp=models.DateTimeField(blank=True) content=RichTextField(blank=True, null=True) def __str__(self): return self.title + " by " + self.author class BlogComment(models.Model): sno= models.AutoField(primary_key=True) comment=models.TextField() user=models.ForeignKey(User, on_delete=models.CASCADE) post=models.ForeignKey(Post, on_delete=models.CASCADE) parent=models.ForeignKey('self',on_delete=models.CASCADE, null=True ) timestamp= models.DateTimeField(default=now) def __str__(self): return self.comment[0:13] + "..." + "by" + " " + self.user.username Html page <h2 class="blog-post-title">{{post.title}}</h2> <p … -
Making search bar in django
Im trying to make a search bar in django and watched several youtube totorials and none of those worked. What im trying to do is either make a search bar that redirects to articles/what_you_searched_for or if not possible show up results that include search. If someone has enough time they can tell me how to do both :). in views.py: def index(request): queryset = article.objects.all() number_of_records = article.objects.count() random_page = random.randint(1,number_of_records) context = { "object_list": queryset, "random_page": random_page } # query = "" # if request.GET: # query = request.GET['q'] # context['query'] = str(query) entries = util.list_entries() return render(request, "encyclopedia/index.html", context) #{ #"entries": util.list_entries(), #"random_page": random_page, #}) def dynamic_articles_view(request, my_id): obj = article.objects.get(id= my_id) number_of_records = article.objects.count() random_page = random.randint(1,number_of_records) context = { "object": obj, "random_page": random_page } return render(request, "encyclopedia/article_detail.html", context) in index.html: {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <h1 id="demo" onclick="add_article()">Article</h1> <ul> {% for instance in object_list %} <li><a href = "http://127.0.0.1:8000/articles/{{instance.id}}/">{{instance.title}}</a></li> {% endfor %} </ul> {% endblock %} layout.html: ------------ SEARCH BAR HERE --------- {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static … -
NOT NULL constraint failed: sistema_clientes.tel
Im currently working on a proyect that uses Django for the back-end and ajax to POST and GET data. The problem is that i dont understand why "NOT NULL containt failed" error ocurred.. I thought that when a models field was "Blank=True", Null data was passed as Blank Data. This is my MODEL: class CLIENTES(models.Model): nombre = models.CharField(max_length=264) razon_social = models.CharField(max_length=264) direccion = models.CharField(max_length=264) localidad = models.CharField(max_length=264) condicion_iva = models.CharField(max_length=264) cuit = models.PositiveIntegerField() expreso = models.CharField(blank=True, max_length=264) domicilio = models.CharField(max_length=264) destino_transporte = models.CharField(max_length=264) descuento = models.PositiveIntegerField(default=0) observacion = models.CharField(blank=True, max_length=264) mail = models.EmailField(blank=True, max_length=264) tel = models.IntegerField(blank=True) fecha = models.DateTimeField(auto_now_add=True) proveedor = models.BooleanField(default=False) Views.py def crear_cliente(request): form = clientes_form(request.POST or None) data = {} if request.is_ajax(): if form.is_valid(): nombre = form.cleaned_data.get('nombre') try: cliente = CLIENTES.objects.get(nombre=nombre) data['nombre'] = cliente.nombre data['status'] = 'notOk' return JsonResponse(data) except: form.save() data['nombre'] = form.cleaned_data.get('nombre') data['status'] = 'ok' data['newUrl'] = HttpResponseRedirect(reverse("sistema:clientes")).url return JsonResponse(data) Ajax form.addEventListener('submit', e=>{ e.preventDefault() const fd = new FormData() fd.append('csrfmiddlewaretoken', csrf[0].value) fd.append('nombre', nombre.value) fd.append('razon_social', razon_social.value) fd.append('direccion', direccion.value) fd.append('localidad', localidad.value) fd.append('condicion_iva', condicion_iva.value) fd.append('cuit', cuit.value) fd.append('expreso', expreso.value) fd.append('domicilio', domicilio.value) fd.append('destino_transporte', destino_transporte.value) fd.append('descuento', descuento.value) fd.append('observacion', observacion.value) fd.append('mail', mail.value) fd.append('tel', tel.value) fd.append('proveedor', proveedor.value) $.ajax({ type: 'POST', url: url, enctype:'text/plain', data: fd, success: function(response){ console.log(response) if (response.status == 'notOk') … -
changing the language of CharFields and IntFields to persian
I have some fields that I want to that fields accept Persian language too. now when I want to add a name for my products I use Persian and English both together but it doesn't shown correctly. and also I want to add a price for products in Farsi (Persian) but the field write it English. I'm using Django rest framework settings: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Tehran' USE_I18N = True USE_L10N = True USE_TZ = True -
Django-React-Heroku Deploy cannot load frontend components. It loads as text instead
I have an combo app with Django backend and Reactjs frontend. During deployment, the backend works just fine (ex. django admin works) but the frontend is loading the html as text (including the tags and everything) instead of a functional webpage ex. My current homepage path would show (as is) <!doctype html><script src="https://unpkg.com/react/umd/react.production.min.js" crossorigin></script>... my urls.py serves the index.html by doing path('', TemplateView.as_view(template_name='index.html', content_type="application/javascript")), and my staticfiles settings are as such STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I also put "postinstall": "npm run build" in package.json under scripts as one of the tutorials suggests. Most of the tutorials online only has one homepage url and no other urls in urls.py, and they are using re_path instead of just path. Maybe that's the issue? -
Django ManyToMany Multiselect Won't Update After Saving
I'm implementing my models like this in Django. class DashboardItem(models.Model): title = models.CharField(max_length=40, blank=True, null=True) content_types = models.ManyToManyField( 'ContentType', blank=True, limit_choices_to={'option_in_dashboard': True},) def __str__(self): return "%s" % self.title or None class ContentType(models.Model): label = models.CharField(max_length=32, blank=False, null=False) def __str__(self): return "%s" % self.label or None When I initially save the DashboardItem using the multi-select field that is generated based on this model it works just fine and will reload with the correct content_types selected. However, if I attempt to update the DashboardItem's content_types by selecting anything different it will save the model without validation errors, reload the page, and then revert back to the original content_types that were saved when initially creating the DashboardItem -
Django rest framework serializer dynamic fields with many=True
I want my serializer return fields dynamically depends on value of some model field. So I override get_fields method. Here's the code example: class TestSerializer(serializers.ModelSerializer): options = serializers.StringRelatedField() blanks = serializers.StringRelatedField() class Meta: model = MyModel fields = ('id', 'category', 'options', 'blanks') def get_fields(self): fields = super().get_fields() if self.instance.category == 'FirstCategory': del fields['options'] else: del fields['blanks'] This works fine when to serialize a single model, but if pass many=True for multiple models, it fails. The self.instance is a QuerySet. How can I deal with this situation? -
django logout from admin without clearing all session
I have a User model class User(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField(null=False, blank=False, max_length=64) last_name = models.CharField(null=False, blank=False, max_length=64) email = models.CharField(null=False, blank=False, unique=True, max_length=64) password = models.CharField(null=False, blank=False, max_length=64) I created a LoginMiddleware that will add a boolean variable containing wether there is a user logged in or not class LoginMiddleware(MiddlewareMixin): def process_request(self, request): request.current_user = self.get_user(request) request.is_user_logged = request.current_user != None def get_user(self, request): try: return User.objects.get(id=request.session['user_id']) except Exception as e: print(str(e)) # gives key error because admin logout clears all session variables return None This is how I use it : def account(request): if not request.is_user_logged: return redirect('/login/') I realized that when I logout from admin my current user is also logged out, as the default behaviour clears all the session variables, including user_id which is set during login KeyError at /account/ 'user_id' -
Sqlalchemy unique constraint with foreign key column and where condition
class Roles(Base): id = Column(UUID(as_uuid=True), default=uuid.uuid4, primary_key=True) name = Column(String) class User(Base) id = Column(UUID(as_uuid=True), default=uuid.uuid4, primary_key=True) name = Column(String) class Department(Base) id = Column(UUID(as_uuid=True), default=uuid.uuid4, primary_key=True) name = Column(String) user_id = Column(UUID(as_uuid=True), ForeignKey('User.id'),nullable=False) role_id = Column(UUID(as_uuid=True), ForeignKey('Role.id'),nullable=False) I want to add unique constraint for user and role in department table only if role = Admin. Else no restrictions. I tried below unique index but not working. Index('ix_department_role_user', Department.user_id, Department.role_id, unique=True, postgresql_where=(Role.name == 'Admin') ) Anyone have any other suggestions please help. Thanks in Advance. -
Django Nginx Not Serving Static Files
First of all, I am very sorry to ask this question as there are hundreds of related questions. The problem is, all these questions are given different answers that seem to work for some people but never for everyone. So far none of the answers worked for me and I have tried (for as far as I know) almost every possible combination of static paths that are suggested. What I have currently and findings Development server works just fine and shows all images (etc.) as expected The static files are being copied into the expected folder (I believe by Django) Current Nginx configuration contains: location /static { alias /usr/local/apps/snipperson-rest-api/static; } Here I have tried location static and the end of the alias with and without static and I tried a lot of different /static/, static/ etc. combinations. Currently in my settings.py I have: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' Also tried STATIC_ROOT = 'static' without BASE_DIR Folder Structure Not sure if this matters but I will add it as extra info. I have my project setup as followed (simplified): /Project /api_app /website /static Every answer that I can find on other posts gives a different suggestion to how … -
how can i display error messages when using the inbuilt reset password and password change in Django
I am working on some user forgot password as well as password reset using Django Built in functionality but I am making use of my template to render the page and form. I will like a way to render the messages either error or success messages so that the user understands what is going on in case the password is too short or so. urls.py from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path('', views.Dashboard, name='dashboard'), path('login/', views.Login, name='login'), path('logout/', views.Logout, name='logout'), path('register/', views.Register, name='register'), path('forgetpassword/', views.ForgetPassword, name='forgetpassword'), path('password_change/', auth_views.PasswordChangeView.as_view( template_name='auth/password/change-password.html'), name='password_change'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view( template_name='auth/password/change-password-done.html'), name='password_change_done'), change-password.html {% extends 'auth/base.html' %} {% load static %} {% block content %} <div class="page-wrapper" style="height: 100vh!important;"> <div class="page-content--bge5"> <div class="container"> <div class="login-wrap"> <div class="login-content"> <div class="login-logo"> <a href="#"> <img src="{% static 'images/icon/logo-new.png' %}" alt="CoolAdmin"> </a> </div> {% if messages %} {% for message in messages %} <div class="alert alert-{{message.tags}} with-close alert-dismissible fade show"> {{message}} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {% endfor %} {% endif %} <div class="login-form"> <form method="POST"> {% csrf_token %} <div class="form-group"> <label>Current Password</label> <input class="au-input au-input--full" type="password" name="old_password" id="id_old_password" placeholder="Current Password" required> </div> <div class="form-group"> <label>New Password</label> … -
Django REST and React - Cookie not getting set in browser but working with postman
Hey guys I am stuck for 2 days trying to solve the issue with django set_cookie, I went through some of the SO answers and found that I had to provide withCredentials:true in the frontend and I have done that, but still it doesn't work. This is the code I have, can someone tell me the error in this? @api_view(['GET', ]) @permission_classes([IsAuthenticated]) def set_cookies(request): if 'currentuser' in request.COOKIES: value = request.COOKIES['currentuser'] return Response({'response':'Cookie is already set'}) else: user = request.user expires = datetime.timedelta(days=30) response = Response() response.set_cookie(key='currentuser', value=user.username, expires=expires, secure=False, httponly=True, samesite='Lax') return response test.js // async function userSetCookie(){ // if(cookies.get('currentuser')) { // console.log('already set') // }else { // await axiosInstance.get('api/user/set_user_cookie/', {withCredentials: true}) // } // } -
Get a Django List - Dict in javascript
I have the following problem with Django. I am sending a List to Javascript and I spect to get this result in the browser. Instance of this looks like my code ignore everything what I do. My code looks like this view.py import itertools from django.shortcuts import render from django.views.generic import TemplateView from django.http import HttpResponse, JsonResponse import json def index(request): return render(request, 'home.html') class UsageView(TemplateView): template_name = 'overview.html' def getFTest(request): ..... context = {"Features": dataFeature} json_context = json.dumps(context) return render(request, "overview.html", {"context_array" : json_context}) url.py from django.contrib import admin from django.urls import path from .views_ import index, getFTest # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path(r'^admin/', admin.site.urls), path('', index, name="home"), path('overview', LicUsageView.as_view(), name="overview"), path('', getFTest, name="getFTest"), ] overview.html var test = ["{{ context_array|safe }}"]; console.log(test); result from the console: an empty List Can somebody tell me where my error ist? Thanks very much -
How to force python keep variable in memory (cache)?
I have a python memory management problem. I have a django application running on windows that loads a 2gb model in memory (using dictionary and numpy). The problem happens when I run this application in the background (using the windows scheduler), after some time without requests, python frees dictionary memory by storing the values on disk. When I have requests again, python loads these values in memory again, caching again, which ends up increasing the response time of the first requests (normalizing right after, when the values are in memory again) I wonder if there is any way to force python to keep these variables in cache, so that it does not do this management on its own. -
ValueError too many values to unpack (expected 2) when using dynamic options in form
I am trying to use a ChoiceField with Django Forms to set up a dropdown field for category selection that should be updated dynamically whenever a category is added. For the dynamic update I use the init function of the Form: class CreateForm(forms.Form): title=forms.CharField(xxx) description = forms.CharField(xxx) URL = forms.CharField(xxx) starting_price = forms.IntegerField(xxx) def __init__(self, *args, **kwargs): super(CreateForm, self).__init__(*args, **kwargs) self.fields['category'] = forms.ChoiceField(choices=[value['category'] for value in Category.objects.all().values('category')]) The Category object is a model with a single entry, namely category = models.CharField(). Now, in the Django doc it mentions that any iterable for choices will work. So in theory a list should work (the above gives me a list like so ['furniture', 'appliances', 'cars']). However, I get a ValueError: too many values to unpack (expected 2). I also have tried to wrap the list in a list() statement, same outcome. Trying a tuple like so ([value['category'] for value in Category.objects.all().values('category')],) which shouldn't make sense, gives the same outcome. Can anybody tell me what's going on? -
Embed Plotly Graph in Django Blog
I'm trying to embed plotly graphs into a django blog that I have. I have created the graphs in jupyter. I am successfully able to add them in, but they disappear every time I edit the blog post. I currently use the following code to get the html I need: rev_div=plot(rev, output_type='div', include_plotlyjs="cdn") print(rev_div) I then copy this code, open my django blog in admin, and enter the code into the source (using ckeditor richtexteditor). If I then save it, it works, and when I go to the blog post I see the graph. Unfortunately, when I try to edit the post again, it disappears and I have to re-add all html graphs again. Does anyone know why it would do this? and how I can solve this? Thanks! -
django does not display form errors
I'm trying to display errors when a user try to login/register with wrong information I have this codes but errors does not show in browser I've wrote this code by looking to another project that I done when I was learning Django but now it's not working! hers is codes of my project views.py : def loginPage(request): if request.user.is_authenticated: return redirect('/') form = loginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') content = { "form": loginForm, "title": "Login", } return render(request, 'login.html', content) #--------------------------------------------- def registerPage(request): if request.user.is_authenticated: return redirect('/') form = registerForm(request.POST or None) content = { "form": registerForm, "title": "Register", } if form.is_valid(): username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') password2 = form.cleaned_data.get('password2') User.objects.create_user(username=username, email=email, password=password) return redirect('/') return render(request, 'register.html', content) forms.py : class loginForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={ "class": "form-control", })) password = forms.CharField(widget=forms.PasswordInput(attrs={ "class": "form-control", })) class registerForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={ "class": "form-control", })) email = forms.EmailField(widget=forms.EmailInput(attrs={ "class": "form-control", })) password = forms.CharField(widget=forms.PasswordInput(attrs={ "class": "form-control", })) password2 = forms.CharField(widget=forms.PasswordInput(attrs={ "class": "form-control", }), label='Password Confirm') def clean_username(self): user_name = self.cleaned_data.get("username") user_exists = User.objects.filter(username=user_name).exists() if user_exists: raise forms.ValidationError("Username is … -
Django Apscheduler: Error getting due jobs from job store 'default': connection already closed
I have configured django-apscheduler in my django project. I am getting error of gettig due job store. I used these configuration. in my settings.py file. SCHEDULER_CONFIG = { "apscheduler.jobstores.default": { "class": "django_apscheduler.jobstores:DjangoJobStore" }, 'apscheduler.executors.processpool': { "type": "threadpool" } } SCHEDULER_AUTOSTART = True Also I have created a scheduler.py file parallel to settings.py with these code lines. import logging from apscheduler.schedulers.background import BackgroundScheduler from django.conf import settings scheduler = BackgroundScheduler(settings.SCHEDULER_CONFIG,job_defaults={'misfire_grace_time': 15*60},deamon=True) def createJob(func, params, tz, id, hour='*', minute='*', ): scheduler.add_job(func, 'cron', params, hour=hour, minute=minute, timezone=tz, id=id) def printJob(): try: scheduler.print_jobs() except Exception as e: pass def removeJob(id): try: scheduler.remove_job(id) except Exception as e: pass def start(): if settings.DEBUG: logging.basicConfig() logging.getLogger('apscheduler').setLevel(logging.DEBUG) scheduler.start() start() -
Getting TypeError: 'bool' object is not iterable When trying makemigrations on a custom User model
I was trying to alter the default django user model with a custom model as given bellow, from django.db import models from django.contrib.auth.models import AbstractBaseUser class User(AbstractBaseUser): username = None phone = models.CharField(max_length=16, unique=True) name = models.CharField(max_length=255, default="User") email = models.EmailField(max_length=255, blank=True, null=True) active = models.BooleanField(default=True) admin = models.BooleanField(default=False) consumer = models.BooleanField(default=False) supplier = models.BooleanField(default=False) manager = models.BooleanField(default=False) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] def __str__(self): return self.phone def get_name(self): return self.name def get_full_name(self): return self.name def get_username(self): return self.phone def get_short_name(self): return self.name def get_email(self): return self.email @property def is_consumer(self): return self.consumer @property def is_supplier(self): return self.supplier @property def is_manager(self): return self.manager @property def is_admin(self): return self.admin @property def is_active(self): return self.active Then added this model to setting.py. But when I Run makemigrations it throws the following error. python3 manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/ajith/Python/water/lib/python3.8/site-packages/django/core/management/init.py", line 364, in execute_from_command_line utility.execute() File "/home/ajith/Python/water/lib/python3.8/site-packages/django/core/management/init.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ajith/Python/water/lib/python3.8/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/ajith/Python/water/lib/python3.8/site-packages/django/core/management/base.py", line 327, in execute self.check() File "/home/ajith/Python/water/lib/python3.8/site-packages/django/core/management/base.py", line 356, in check all_issues = self._run_checks( File "/home/ajith/Python/water/lib/python3.8/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/ajith/Python/water/lib/python3.8/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/ajith/Python/water/lib/python3.8/site-packages/django/contrib/auth/checks.py", … -
os.path.expanduser("~") not working on heroku
I'm having issue with youtube_dl path configuration in django. Based on the below configuration, its working properly in development mode but when hosted on heroku, the downloaded resources could not be traced anywhere. # Download view def download(request): details = [] if request.method == 'POST': v_url = CreateURL(request.POST) if v_url.is_valid(): video_url = v_url.cleaned_data['url'] #path configured homedir = os.path.expanduser("~/Downloads/%(title)s.%(ext)s") try: ydl = youtube_dl.YoutubeDL( { '-f best': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best', '-o': f'{homedir}', # 'progress_hooks': [my_hook], }) with ydl: result = ydl.extract_info( video_url, download=True # We just want to extract the info ) if 'entries' in result: # Can be a playlist or a list of videos video = result['entries'][0] else: ` # Just a video` video = result video_data= { 'resolution':video['thumbnails'][3]['resolution'], 'title':video['title'], 'ext':video['ext'], } details.append(video_data) except: messages.warning(request,"Error in downloading the video, please check your network connection and try again!") else: messages.success(request, 'Downloaded successfully, check your download folder for details!') context={ 'details':details } return render(request, 'download.html', context ) Any help will be appreciated. Thanks -
Reload Gunicorn in Docker on HTML File Change
My application is SaaS based and allows users to customise their frontend HTML specific to their account (it's a store software), by giving them access to HTML and CSS files through a code editor in the browser. It's using Docker Compose running Gunicorn as the entry point for the web container. When the user makes changes to the HTML pages, the changes aren't reflected live. I understand that Gunicorn has the --reload flag and I've tried using this. Unfortunately for that command to work I need to enable Debug mode which is a no go. Plus, I don't want to reload the entire application, just only when HTML files change. I ran the application outside of Docker on a separate VM with the --reload-extra-file Gunicorn command and was able to get it to reload, with Debug turned off. Like this: --reload --reload-extra-file /path/to/folder However when I do this within the Docker container using this as the command in Docker Compose: gunicorn --chdir /home/someDir MyApp.wsgi:application --bind 0.0.0.0:8000 --reload --reload-extra-file /path/to/folder It doesn't work. If I change to Debug mode it does or if I reload the Docker container it does. Is there a solution to do this with Gunicorn? Or is … -
FileField Upload to not working as expected in Django
I have a django code , which should upload a file which is entered through a filefield to be uploaded to a particular path for example i have a folder named "Uploadfiles" , so i just want my files entered in file field to be uploaded in that folder . i tried , but my file is not getting uploaded to that folder . so below is my code : class Uploadedfile(models.Model): def file_path(self, filename): return f'uploaded_files/{self.server}/{self.path.replace(":", "$", 1)}/{filename}' files_to_upload = models.FileField( upload_to=file_path, default=None, validators=[validate_file] ) path = models.CharField(max_length=100) server = MultiSelectField(choices=server_list) salesforceticket = models.ForeignKey( Salesforceticket, related_name='uploadedfile', on_delete=models.CASCADE ) def __str__(self): return str(self.salesforceticket) since am new to django , i don know whether i made any mistake . Can anyone please help me out in this -
KeyError at /accounts/login/ 'email'
I want to login user via email and password. I'm unable to do that. Please Help me to fix this issue. I shall be very thankful to you. forms.py from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import AuthenticationForm class CustomLoginForm(AuthenticationForm): class Meta: model = User fields = ['email','password'] def __init__(self, *args, **kwargs): super(CustomLoginForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs['placeholder'] = ('Enter your email') self.fields['email'].label = '' self.fields['password'].widget.attrs['placeholder'] = ('Password') self.fields['password'].label = '' models.py class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) If more code is require then tell me in a comment section , I will update my question with that information. Traceback -
Uploaded and Deadline fields in Django models
I am making a to do app and in models I have a Task model and dateTimeFields "uploaded", which has auto_now_add=True. Now I want to add deadline field, where users can add the task deadlines. I tried adding second DateTimeField but there's a problem when I make migrations. here's the code and the powershell warning: models: class Task(models.Model): title = models.CharField(max_length=50) completed = models.BooleanField(default=False) uploaded = models.DateTimeField(auto_now_add=True) deadline = modles.DateTimeField() def __str__(self): return self.title powershell: *You are trying to add a non-nullable field 'deadline' to task without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py Select an option:* -
I exported the environment variable from entrypoint, but why can't I see it when I printed it in the docker container?
I exported environment variables but cannot check at the container with a command below. docker exec -it {containerID} bash printenv docker-copose.yml ... services: django: build: context: . dockerfile: ./Dockerfile image: django container_name: django depends_on: - postgres env_file: - ./.envs/.local/.django ports: - "8000:8000" command: /start ... Dockerfile ... ENTRYPOINT ["/entrypoint"] entrypoint #!/bin/sh set -e echo >&2 echo !!!!!!!!!!!!!!!!!!!!! echo >&2 echo ${DJANGO_SETTINGS_MODULE} echo >&2 echo DJANGO_SETTINGS_MODULE Actually everything works fine. results What I am curious about is where is the environment exported by entrypoint? Why can't I check inside the container?