Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Hostname mismatch, certificate is not valid for 'localhost'. (_ssl.c:997)
Exception Location: /usr/lib/python3.10/ssl.py, line 1342, in do_handshake I am new webi. I get this error when sending email from my django website. I have two domains on the host and am using postfix to send emails i have checked ssl certificates and are working properly. can anyone help please i tried to pip install -upgrade certifi to update the certificates. renewed the certificates with sudo certbot renew --dry-run the site is also active with https -
While testing routes of my django prodject, i got Type error: expected sting or bites like object. How i can fix this error?
The page of the published news on my blog, is available to any user. I use pytest to check if the page is accessible to an anonymous user. Url is formed by using the id of the news, which I pass in the address parameters (as a tuple). In the result I got this Type error. test_pages_availability[news:detail-news] - TypeError: expected string or bytes-like object I had tried to format args to str, puted a coma after arg for tuple format, it didn't helped code of test @pytest.mark.django_db @pytest.mark.parametrize( 'name, args', ( ('news:detail', pytest.lazy_fixture('news')), ('news:home', None), ('users:login', None), ('users:logout', None), ('users:signup', None), ) ) def test_pages_availability(client, name, args): if args is not None: url = reverse(name, args=(news.id,)) else: url = reverse(name) response = client.get(url) assert response.status_code == HTTPStatus.OK ` fixture @pytest.fixture def news(): news = News.objects.create( title='Новость', text='Невероятное событие', date=datetime.today, ) return news class NewsDetail(generic.DetailView): model = News template_name = 'news/detail.html' def get_object(self, queryset=None): obj = get_object_or_404( self.model.objects.prefetch_related('comment_set__author'), pk=self.kwargs['pk'] ) return obj def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.user.is_authenticated: context['form'] = CommentForm() return context Traceback: request = <FixtureRequest for <Function test_pages_availability[news:detail-news]>> def fill(request): item = request._pyfuncitem fixturenames = getattr(item, "fixturenames", None) if fixturenames is None: fixturenames = request.fixturenames if hasattr(item, … -
Upgrading Redis on Heroku causing SSL errors in Celery
I've recently upgraded our Heroku Redis from version 5.0 to 7.0.11 and I'm now receiving the following error when running Celery Traceback (most recent call last): File "/app/.heroku/python/bin/celery", line 8, in <module> sys.exit(main()) File "/app/.heroku/python/lib/python3.8/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/app/.heroku/python/lib/python3.8/site-packages/celery/bin/celery.py", line 235, in main return celery(auto_envvar_prefix="CELERY") File "/app/.heroku/python/lib/python3.8/site-packages/click/core.py", line 1130, in __call__ return self.main(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/click/core.py", line 1055, in main rv = self.invoke(ctx) File "/app/.heroku/python/lib/python3.8/site-packages/click/core.py", line 1657, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/app/.heroku/python/lib/python3.8/site-packages/click/core.py", line 1404, in invoke return ctx.invoke(self.callback, **ctx.params) File "/app/.heroku/python/lib/python3.8/site-packages/click/core.py", line 760, in invoke return __callback(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/click/decorators.py", line 26, in new_func return f(get_current_context(), *args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/celery/bin/base.py", line 134, in caller return f(ctx, *args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/celery/bin/worker.py", line 348, in worker worker = app.Worker( File "/app/.heroku/python/lib/python3.8/site-packages/celery/worker/worker.py", line 98, in __init__ self.setup_instance(**self.prepare_args(**kwargs)) File "/app/.heroku/python/lib/python3.8/site-packages/celery/worker/worker.py", line 119, in setup_instance self._conninfo = self.app.connection_for_read() File "/app/.heroku/python/lib/python3.8/site-packages/celery/app/base.py", line 818, in connection_for_read return self._connection(url or self.conf.broker_read_url, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/celery/app/base.py", line 877, in _connection return self.amqp.Connection( File "/app/.heroku/python/lib/python3.8/site-packages/kombu/connection.py", line 203, in __init__ url_params = parse_url(hostname) File "/app/.heroku/python/lib/python3.8/site-packages/kombu/utils/url.py", line 50, in parse_url query['ssl'][key] = query[key] TypeError: 'str' object does not support item assignment celery.py from celery import Celery app = Celery('endpoints') # namespace='CELERY' means all celery-related configuration keys should have a … -
How can I load SECRET_KEY from .env file in Django?
This is how my settings.py looks like: import os import dotenv dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) # UPDATE secret key SECRET_KEY = os.environ['SECRET_KEY'] This is how my .env file looks like: SECRET_KEY="TOPSECRETKEY" When running python manage.py migrate, it returns KeyError: 'SECRET_KEY' -
Template is not saving Image to database
I am developing a website that allows users to upload projects with various details such as name, description, image, and deadline. However, I am facing an issue where, upon clicking the "Save Project" button, i get redirected to the homepage, but the image does not get saved in the database while everything else does. No error message is displayed. The problem may lie in the form and script sections since it has been able to save image, but after making adjustments to the form and adding script code, to make it look nicer, it stopped working. Screenshot of input form: (https://i.stack.imgur.com/ZUVrC.png) Screenshot of homepage after saving a project: (https://i.stack.imgur.com/wrb0o.png) Here is my code: form that was able to save images: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="{{ project_form.project_name.id_for_label }}">Project name:</label> {{ project_form.project_name }} <br> <label for="{{ project_form.project_description.id_for_label }}">Project description:</label> {{ project_form.project_description }} <br> {{ formset.management_form }} {% for form in formset %} <div class="formset-row"> {{ form.id }} {{ form.image }} </div> {% endfor %} <br> <label for="{{ project_form.deadline.id_for_label }}">Deadline:</label> {{ project_form.deadline }} <br> <button type="submit">Save Project</button> </form> In models.py: from django.db import models class Project(models.Model): project_name = models.CharField(max_length=100) project_description = models.CharField(max_length=2000) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True,) deadline = models.DateTimeField(null=True, … -
How to show/hide a django form field based on the stored value while editing?
models.py: cv_choices = ( ('One Time', 'One Time'), ('Renewal', 'Renewal'), ) class Certification(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE, null=True) certName = models.CharField(_('Certification Name'), max_length=100, null=True) certId = models.CharField(_('Certification ID'), max_length=100, null=True) certUrl = models.URLField(_('Certification URL'), max_length=500, null=True) certStartDate = models.DateField(_('Certification Start Date'), null=True) certEndDate = models.DateField(_('Certification End Date'), null=True, blank=True) certValidity = models.CharField(_('Certification Validity'), max_length=10, choices=cv_choices, default='Renewal', null=True) createdDate = models.DateTimeField(_('Created Date'), auto_now_add=True, editable=False) modifiedDate = models.DateTimeField(_('Modified Date'), auto_now=True, editable=False) def __str__(self): return self.certName forms.py: class CertificationForm(forms.ModelForm): certValidity = forms.ChoiceField(choices=[('One Time', 'One Time'),('Renewal', 'Renewal')]) class Meta: model = empCertification fields = ('user', 'certName', 'certId', 'certUrl', 'certStartDate', 'certEndDate', 'certValidity') def __init__(self, *args, **kwargs): super(empCertificationForm, self).__init__(*args, **kwargs) self.fields['user'].widget.attrs['class'] = 'form-select' self.fields['certName'].widget.attrs['class'] = 'form-control' self.fields['certId'].widget.attrs['class'] = 'form-control' self.fields['certUrl'].widget.attrs['class'] = 'form-control' self.fields['certStartDate'].widget.attrs['class'] = 'form-control' self.fields['certEndDate'].widget.attrs['class'] = 'form-control' self.fields['certValidity'].widget.attrs['class'] = 'form-select' for field in self.fields: self.fields[field].widget.attrs['placeholder'] = 'Provide Details' Edit Template File: <form action="{% url 'certificationEdit' certification.pk %}" method="post" class="form" enctype="multipart/form-data" novalidate> {% csrf_token %} <div class="card-body border-top p-9"> {% if certificaitonForm.errors %} {% for field in certificaitonForm %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{field.name|title}} - {{error|escape}}</strong> </div> {% endfor %} {% endfor %} {% for error in certificaitonForm.non_field_errors %} <div class="alert alert-danger"> <strong>{{error|escape}}</strong> </div> {% endfor %} {% endif %} <div … -
Django: Problem with urlpatterns for a page after login
After login, i can't access the redirect page (home.html). The page is not found, because I misspelled the urlpatterns of the home page. I'm new to Django. In urlpatterns work fine correctly: index page, login page and logout page. But the home page doesn't. I believe the problem is the urlpatterns of the home. The page is located at templates/app1/home.html Project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('app1.urls')) App/urls.py from django.urls import path, include from . import views from app1.views import index from app1 import views urlpatterns = [ path('', index, name='index'), path('login/', views.sign_in, name='login'), path('logout/', views.sign_out, name='logout'), path('home/', views, name='home'), #ERROR HERE??? ] In views.py I don't have any home related functions. I only have the login/logout functions working correctly. How can I display the home correctly? -
Django models anotate Count always return 1
Hello I have Django model like this: class Order(models.Model): order_id = models.CharField(max_length=100) title = models.TextField(max_length=600) title_2 = models.TextField(max_length=100) attempts = models.ForeignKey('self', blank=True, null=True, on_delete=models.PROTECT) driver = models.ForeignKey(Driver, blank=True, null=True, on_delete=models.SET_NULL) The main flow I have orders attempts=None and I want to Count of all objects which consist pk in attempts by specific instance. And I use smth like that: order = Order.objects.filter(driver_id=pk).annotate(re_exec=Count('attempts')) And It always returned 1 but it isn't correct. How I can correctly Count this objects ? -
Cannot resolve expression type, unknown output_field - Return model instances in Django's Coalesce?
I have an endpoint that will display results from a model. There's going to be a image illustrating each result, and if none of the posts of this category has a media associated, I'll get the writers avatar to display it. I can get the media url value using the .values('media_source') method in the subqueries, but the problem is that the serializer expects a complex model with other fields and properties. I've tried to use the code below to in order to get the instances, but I receive the following error: Cannot resolve expression type, unknown output_field I understand that I'd need to specify a field type (such as CharField, etc) but I can't figure out if there's a type that is actually interpreted as a Django model instance. def get_queryset(self): annotation = Coalesce( Subquery(PostMedia.objects.filter(categories=OuterRef('pk'))), Subquery(UserMedia.objects.filter(posts__categories=OuterRef('pk'))) ) return Categories.objects.filter(is_public=True).annotate(media_source=annotation) -
Can run the django and react js app on same ec2 instace and point them to a domain separately for each?
I have a django app running on http://public ip of ec2:8000 on ec2 and then i have created a nginx server and its sever is like this server listen 80; server_name public ip of ec2; location proxy_pass http://public ip of ec2:8000/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; And then i have pointed it to the a domain like server.domain.com in dns by adding a A record pointing to ec2 public ip. Now i have also created the react js and deployed it on same ec2 and started running it using pm2 on http://public ip ec2:3000/. Django:8000 and react js:3000 are running on different ports. "Now how can i point it to another domain like frontend.domain.com in the dns ? As i won't have another public ip for that ec2" which if there i can create another nginx and point it to the domain in dns. I have a django app running on http://public ip of ec2:8000 on ec2 and then i have created a nginx server and its sever is like this server listen 80; server_name public ip of ec2; location proxy_pass http://public ip of ec2:8000/ And then i have pointed it to the a domain like server.domain.com in dns … -
D3.js linechart (v3) shows line and tooltip coordinates but the coordinate text sticks to screen even when moving mouse
I have code written in js d3. I have a functioning line chart and tooltip but the text sticks on the screen when moving the mouse and only large moves of the mouse remove the text. How do I fix it so that only the current coordinates show and when the mouse moves the old coordinates disappear? code: ` ` var foWidth = 300; var anchor = {'w': width/3, 'h': height/3}; var t = 50, k = 15; var tip = {'w': (3/4 * t), 'h': k}; var fix_resize = 200; // Set the color scale, if multi chart lines var color = d3.scale.category10(); var margin = {top: 30, right: 20, bottom: 30, left: 50}, width = 600 - margin.left - margin.right + fix_resize, height = 270 - margin.top - margin.bottom + fix_resize; //var parseDate = d3.time.format("%Y-%m-%d").parse; function getDate(d) { return new Date(d.date); } var minDate = getDate(data[0]), maxDate = getDate(data[data.length-1]); var x = d3.time.scale().domain([minDate, maxDate]).range([0, width]); var y = d3.scale.linear().range([height, 0]); var xAxis = d3.svg.axis().ticks(d3.time.months, 1).tickFormat(d3.time.format("%b %Y")).scale(x) .orient("bottom").ticks(6); var yAxis = d3.svg.axis().scale(y) .orient("left").ticks(6); // def the area under the line var area = d3.svg.area() .interpolate("basis") .x(function(d) { return x(d.date); }) .y1(function(d) { return y(d.target_downside_base); }) .y0(function(d) { return y(0); … -
Django view won't save image uploaded through AJAX using .fetch
I'm having a problem with my tweet image not saving to my model when my tweet form is submitted. The other content of the tweet such as the tweet itself has no problem saving but the image is where the issue lies. I am submitting my form using AJAX, and making the appropriate call to the view to save the tweet content to the Tweet model. When I print the values of request.FILES and request.POST, this is what I get ('test' is what I have inputted for my tweet field for demonstration): <MultiValueDict: {}> <QueryDict: {'tweet': ['test']}> views.py def post_tweet(request): if request.method == "POST": print(request.FILES, request.POST) # Get contents of form tweet = request.POST.get("tweet", "").strip() # This doesn't capture the image passed. image = request.FILES.get("tweet-picture") # Save the tweet to the model new_tweet = Tweet.objects.create(tweet=tweet, user=request.user, image=image) new_tweet.save() return JsonResponse({"message": "Tweet created successfully."}, status=201) else: return JsonResponse({"error": "POST request required."}, status=400) JS code that handles request (Within my DOMContentLoaded Listener) const tweetForm = document.querySelector("#tweet-form"); tweetForm.addEventListener('submit', function(event) { event.preventDefault(); // Stops other event listeners of the same type of being called event.stopImmediatePropagation(); const tweetInput = document.getElementById("post-content"); const tweet = tweetInput.value; let tweetImage = ""; try { const tweetImageElement = document.querySelector("#tweet-picture-preview img"); … -
Django api and react axios post dont work
am trying to make a simple api where a user writes something in a field, presses a button and a new instance is added in the database. To do this I am using react and django rest framework. App.js const [name,setName] = useState('') const handleChange = (e) => { setName(e.target.value) } function handleClick(e) { fetch('127.0.0.1:8000/post/', { method: 'POST', headers: { 'Content-type': 'application/json' }, body: JSON.stringify({ name:'a', title:'b' }) }) } return ( <> <form> <input type='text' value={name} onChange={handleChange} /> <button onClick={handleClick}>OK</button> </form> </> ); views.py @api_view(['POST']) def home2(request): serializer = ItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) urls.py from django.urls import path from . import views urlpatterns = [ path('api/',views.home,name='home'), path('post/',views.home2,name='home2'), path('a/',views.home3,name='home3') ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'main', 'corsheaders' ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True But when I press the button I get manifest.json:1 GET http://127.0.0.1:8000/manifest.json 404 (Not Found) and manifest.json:1 Manifest: Line: 1, column: 1, Syntax error. in javascript. In django I get "POST /post/ HTTP/1.1" 200 0 Also I am using npm run build for javascript and manifest.json is in public folder. React is inside django and the structure looks like this: mysite frontend main mysite db.sqlite3 manage.py Also when I … -
Gunicorn error: "ModuleNotFoundError: No module named 'ckeditor'"
I am trying to do nginx on aws with this film Deploy a Django web app with Nginx to Amazon EC2 but im stuck on 24 min... When i'm trying to check gunicorn status with sudo supervisorctl status i got massage FATAL Exited too quickly (process log may have details) I found error log and this is what it said ModuleNotFoundError: No module named 'ckeditor' [2023-06-18 16:51:55 +0000] [16414] [INFO] Worker exiting (pid: 16414) [2023-06-18 16:51:55 +0000] [16411] [WARNING] Worker with pid 16413 was terminated due to signal 15 [2023-06-18 16:51:55 +0000] [16411] [WARNING] Worker with pid 16414 was terminated due to signal 15 [2023-06-18 16:51:55 +0000] [16411] [INFO] Shutting down: Master [2023-06-18 16:51:55 +0000] [16411] [INFO] Reason: Worker failed to boot. [2023-06-18 16:51:57 +0000] [16415] [INFO] Starting gunicorn 20.1.0 [2023-06-18 16:51:57 +0000] [16415] [INFO] Listening at: unix:/home/ubuntu/myapp/app.sock (16415) [2023-06-18 16:51:57 +0000] [16415] [INFO] Using worker: sync [2023-06-18 16:51:57 +0000] [16416] [INFO] Booting worker with pid: 16416 [2023-06-18 16:51:57 +0000] [16417] [INFO] Booting worker with pid: 16417 [2023-06-18 16:51:57 +0000] [16418] [INFO] Booting worker with pid: 16418 [2023-06-18 16:51:57 +0000] [16416] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/ubuntu/env/lib/python3.10/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/home/ubuntu/env/lib/python3.10/site-packages/gunicorn/workers/base.py", … -
why we use login(request, user) and how it works in Django?
I am new to Django. I don't understand why we use login(request,user) to authenticate user to login def login_user(request): if request.method=="POST": username=request.POST.get("username") password=request.POST.get("password") user= authenticate(username=username, password=password) if user is not None: login(request,user) return redirect("home") return render(request,"login.html") -
Django Unable to Migrate to Redshift
I have a django project with multiple apps, that use 3 different databases. I'm using postgresql for my default and prod database and redshfit for users to query and analytics. I have successfully ran migrations to my default and prod databases however, when i try to run a migrations to redshift i get the following error: ProgrammingError: mulitple default values specified for column 'id' of table 'django_migrations'. I have checked the django_migrations table and there are no duplicate id's. Additionally there are no duplicate migrations files in the migrations folder. I have tried multiple different approaches to my custom router, specifically the allow_migrate() method. Below are a couple variations I've tried. My current router.py is below as well. def allow_migrate(self, db, app_label, model_name=None, **hints): apps_list = ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions'] if db in ['default', 'prod', 'redshift']: return True elif db == 'default' and app_label in apps_list: return True else: return False def allow_migrate(self, db, app_label, model_name=None, **hints): if db == 'redshift': return True elif db == 'prod': return True else: return True Note: I'm able to query the redshift database with no issue using django shell, if i build out the models and corresponding table in redshift, so my connection … -
how to make vuejs work fine with for loop of data and input select
i try many solution but problem when select one of choice change all another select option <div class="form-group" v-for="(service , index) in clinicThirdPartyServices" :key="index"> <div class="form-group row mb-6"> <div class="col-md-3"> <label class="form-label">[[service.category]]</label> <input class="form-control form-control-solid" :placeholder="[[service.category]]" /> <input hidden class="form-control form-control-solid" placeholder="{{ thirdparty.category }}" name="service_category" value="{{ thirdparty.category }}" /> </div> <div class="col-md-3"> <label class="form-label">{% translate 'Service' %} </label> <select name="service_supplier" id="thirdparty.category" aria-label="{% translate 'Service' %}" data-placeholder="{% translate 'Service' %}" @click="getThirdPartyServices([[service.owner_id]])" class="form-select form-select-solid fw-bolder"> <option v-for="(item,index) in servicesOfThirdParty" :key="item.slug" :value="[[item.id]]">[[item.title]]</option> </select> </div> <div class="col-md-5"> <label class="form-label">{% translate 'Note' %}</label> <input class="form-control form-control-solid" placeholder="{% translate 'Note' %}" name="service_note" value="" /> </div> </div> </div> i need when select the one of choice select not change the another options to make code run fine -
Django loses permission to my email after an amout of time
I created a couple of urls so that user can reset his password in case he forgot what it was, In the process website should send a mail to the user's registered email to reset his password. The function works well! But after an amount of time I get a timeoutError, I think because django loses permission to access my email from which it will send mails to the users emails. The error I face: TimeoutError at /password-reset/ [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Request Method: POST Request URL: http://127.0.0.1:8000/password-reset/ Django Version: 4.2.1 Exception Type: TimeoutError Exception Value: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Here is where I configured how to send mails in settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'MY EMAIL' EMAIL_HOST_PASSWORD = 'A password that was generated by google app passwords' DEFAULT_FROM_EMAIL = 'noreply<no_reply@domain.com>' password_reset.html {% extends 'retinoscope/base.html' %} {% load … -
Using a Model in a `default` attribute of a model field in Django
I hope what I'm asking makes sense, I'm trying to use a model's attribute as the default value of one of another models fields (I'm not even sure if my wording is correct, so bear with me). Most code has been removed as this is for work Code below: @deconstructible class Placement(BaseModel): id = models.IntegerField(primary_key=True) site = models.CharField(max_length=32, null=True, blank=True, default="fool") ..... default_style = models.TextField(null=True, blank=True, default="<p>Place styling here</p>") ...... class Pitch(PastVersionsLinkMixin, BaseModel): headline = models.CharField(max_length=1024, null=False, blank=True) display_headline = models.CharField(max_length=1024, null=False, blank=True) ..... description = HTMLField(***default=Placement['default_style']***, null=True, blank=True) ..... author = models.TextField(default=None, null=True, blank=True) placement = models.ForeignKey( Placement, help_text="aka vehicle", null=True, blank=False, on_delete=models.SET_NULL, ) default=Placement['default_style'] is what I'm trying to set as the description, but I'm not sure if this is doable, or if I'm just going about it the wrong way.I've tried dot notation as well and no luck, I've even used it's own placement.default_style and I get an error as well. Is this something that can be done or am I SOL? Thanks in advance! -
Django Crispy Forms - Initial value not being set
First time asking for help on this one. I am trying to use crispy forms to improve the layouts on my page. However, when I changed a working page from plain Django form to use Crispy forms the initial value is no longer being set on the form Forms.Py def __init__(self, client_, *args, ** kwargs): super(RecurringEventForm, self).__init__(*args, ** kwargs) self.fields['client'].initial = client_ self.helper = FormHelper() self.helper.form_class = 'form-inline' self.helper.form_method = 'POST' self.helper.layout = Layout( Field('recurring_label', css_class='form-control col-md-2 w-30'), Field('event_type', css_class='form-control col-md-2 w-25'), Field('carer', css_class='form-control col-md-2 w-25'), Row( Column('recurring_start_date', css_class='form-group col-md-2'), Column('recurring_end_date', css_class='form-group col-md-2'), css_class='form-row' ), Row( Column('event_start_time', css_class='form-group col-md-2'), Column('event_end_time', css_class='form-group col-md-2'), css_class='form-row' ), Submit('submit', 'Submit', css_class='btn-primary') ) HTML - that doesn't work {% block content %} <h1>Create Series</h1> <br/><br/> <form action="" method="POST"> {% csrf_token %} {% crispy form %} <a class="btn btn-secondary" href="{% url 'manage_client_schedule' client_id %}">Cancel</a> </form> {% endblock %} when I use the same form definition with the below HTML it sets the initial value correctly HTML - working {% block content %} <h1>Create Series</h1> <br/><br/> <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" class="btn btn-primary"> <a class="btn btn-secondary" href="{% url 'manage_client_schedule' client_id %}">Cancel</a> </form> {% endblock %} I can't find anything in … -
Error Importing Packages In DJANGO:Circular import error python
Please help me with a circular import error I am encountering while importing Gingerit. I am new to Django and currently working on a project named "tut1". I'm in the process of learning Django and have attempted various methods to import the necessary packages. I would greatly appreciate any assistance. Thank you in advance! -
Selecting fallback database in Django3
My Django3 project works in docker using gunicorn+nginx. That connected to remote DBSaaS postgresql cluster: main side + standby side (ReadOnly if not active). How to use another database when the main one is unavailable? This DB setting in my Django3 project now: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'db_main', 'USER': 'user', 'PASSWORD': "!!!!", 'HOST': '1.1.1.5', # MAIN DB 'PORT': '5432', } } Now, if db_main host is unreachable. I manually set another IP in settings (like 1.1.2.4) And relaunch my site. What settings\middle should i use for decide this problem? It necessary for full redundant for my project Surfing not helps me. That docs don't cover my case: https://docs.djangoproject.com/en/4.2/topics/db/multi-db/ Please, give me some links\hints for that. May be there is no native\3rd-party Django-solutions. Should i use nginx scenarios for solve it? Something like: nginx periodically checks postgresql ip availability and if active side is unreach it goes change my settings.py file or import another env variable DATABASE? -
Django break statement not allowed in block tags
Error message: "django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 82: 'break', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?" This error is being caused because I am trying to use the break statement in a block tag in a Django template. To fix this error, I replace it with a return statement from the block tag. Which will terminate the if statement immediately. But the error remains the same. Here is the code: <div class="card"> <h5 class="mb-30">By Categories</h5> <div class="categories-dropdown-wrap font-heading"> <ul> {% for c in categories %} <li> <input data-filter="category" class="form-check-input filter-checkbox" type="checkbox" name="checkbox" id="exampleCheckbox2" value="{{ c.id }}" /> &nbsp;&nbsp; <a href="{% url 'core:category-product-list' c.cid %}"> <img src="{{c.image.url}}" alt="" />{{ c.title }}</a > </li> {% if c.loop.index == 5 %} <li> <p>This is the 5th category.</p> </li> {% break %} {% endif %} {% endfor %} </ul> </div> </div> My goal is to stop the for loops after listing 5 items from the category, Please I need help to fix this issue -
How to connect AWS RDS MySQL from Django app from local machine
when i try to hook up my Django site to a remote MySQL RDS i get the error: makemigrations.py:158: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (1049, "Unknown database 'mydatabaseinstance'") warnings.warn( No changes detected my config in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydatabaseinstance', 'USERNAME': 'xxxxx', 'PASSWORD': 'xxxxxx', 'HOST': 'xxxxxx.xxxx.us-east-1.rds.amazonaws.com', 'PORT': '3306', } } I'm confused because I can connect through MySQL Workbench -
Reload a django view
Hi I have a django app where the usual user can see in the home page a list of services, click on it to read more details and return to home page. User can register (usign django admin) and login. If a user is new he saw only the list of services. When he reads a service the app track the url visited (I'm using django tracking2 https://github.com/bruth/django-tracking2) and it shows some recommendations (they are based on text analysis and similiarity). The logged user to see updated recommendations it needs to logout and login..It seems django doesn't reload the view. These are my files: urls.py from django.contrib import admin from django.urls import path, include from rs import views from django.conf import settings from django.conf.urls.static import static from django.urls import re_path urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name="index"), path('static', views.static, name='static'), path('users/index', views.users_servizi_list, name='user_index'), path('users/detail/<int:pk>/', views.user_dettaglio, name='user_dettaglio'), path('accounts/', include('django.contrib.auth.urls')), path('sign_out', views.sign_out, name='logout'), path('index', views.servizi_list, name='servizi'), path('detail/<int:pk>/', views.dettaglio, name='dettaglio'), re_path(r'^tracking/', include('tracking.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) views.py from django.shortcuts import render from django.http import HttpResponse from django.conf import settings from django.conf.urls.static import static from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth import login, authenticate, logout from django.contrib.auth.decorators import login_required …