Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Elastic Beanstalk server using 97% memory warning
I just discovered that my Elastic Beanstalk server has health status with a warning "97% of memory is in use". Because of this I can not deploy updates or ssh and run the django shell. I just receive the following error: MemoryError Error in atexit._run_exitfuncs: Traceback (most recent call last): File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/sentry_sdk/worker.py", line 70, in start self._thread.start() File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/sentry_sdk/integrations/threading.py", line 54, in sentry_start return old_start(self, *a, **kw) # type: ignore File "/usr/lib64/python3.7/threading.py", line 852, in start _start_new_thread(self._bootstrap, ()) RuntimeError: can't start new thread I received more memory errors when trying AWS documented troubleshooting suggestions which required installing a package: sudo amazon-linux-extras install epel From here I don't know what else I can do to troubleshoot this issue or how to fix it. -
Django - how to automatically create a new model instance when another model instance is created
I have an Order and Notification Model, whenever there is a new order model instance, i want to immediately create a notification for the new order, i wrote some functions in the models but when there is a new order, the notification instance does not get created. i still think there should be a better way to do this, how can i go about this? models.py class Orders(models.Model): service = models.ForeignKey(Service, on_delete=models.SET_NULL, null=True, related_name="service_orders") seller = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="seller") def create_notification(self): create_notification = Notification.objects.create(provider=self.seller, service=self.service, order=self , notification_type='new_order') create_notification.save() return create_notification class Notification(models.Model): provider = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="provider_notifications") service = models.ForeignKey(Service, on_delete=models.SET_NULL, null=True, related_name="service_notifications") order = models.ForeignKey(Orders, on_delete=models.SET_NULL, null=True, related_name="service_order") notification_type = models.CharField(max_length=100, choices=NOTIFICATION_TYPE, default="none") -
Django "DATABASES is improperly configured" error after updating versions
I am trying to update a few-year old existing django project to current django and python 3. We're running into a multitude of issues, but most haven't been to hard to identify and resolve. Currently we are running into the dreaded django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. error when trying to manage.py migrate or some other commands like inspectdb. The odd thing is that we definitely are defining the database config with a default db and engine. This setup below is from our settings.py file. It's set up that way just so that we could use sqlite for testing purposes or mysql like the live servers. I've tried both, and it doesn't work with either. I have put print statements in to confirm that it does hit the appropriate sections. I also tried the dummy engine just to test and that had the same issue. #LOCALDEV_DB = 'MYSQL' LOCALDEV_DB = 'SQLITE' if LOCALDEV_DB == 'MYSQL': DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'foo', 'USER': 'root', 'PASSWORD': '123456789', 'OPTIONS': { 'init_command' : 'SET default_storage_engine=MYISAM', }, #'STORAGE_ENGINE': 'MYISAM' } } elif LOCALDEV_DB == 'SQLITE': DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } The … -
Django CMS page tree default language
It seems I don't understand how to set the default language for Django CMS. I want the default language to be set to Dutch. However, for an unknown reason, it always defaults to English when creating or after modifying/editing a Page. Take the following scenario. I open the Page tree. English is selected. I select Dutch. It I edit this page. I publish it. I refresh the page, I click on edit, it opens the English page which is empty. Note: All cookies were removed as suggested in the documentation. Please advise how I can set the default language to Dutch? The settings: from django.utils.translation import gettext_lazy as _ LANGUAGE_CODE = "nl" SITE_ID = 1 USE_I18N = True MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "corsheaders.middleware.CorsMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.common.BrokenLinkEmailsMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', ] LANGUAGES = [ ('nl', 'Dutch'), ('en', 'English'), ] CMS_LANGUAGES = { 1: [ { 'code': 'nl', 'name': _('Dutch'), 'fallbacks': ['en', ], 'public': True, 'hide_untranslated': True, 'redirect_on_fallback': False, }, { 'code': 'en', 'name': _('English'), 'public': True, }, ], 'default': { 'fallbacks': ['nl', 'en'], 'redirect_on_fallback': False, 'public': True, 'hide_untranslated': True, } } -
Django API: Updating a list of dictionaries
I am trying to pass a list of dictionaries through my django rest framework API, loop through them, update the associated records in the model, and ultimately return the serialized data to the front end. I am receiving the following error when submitting the list of dictionaries: HTTP 400 Bad Request Allow: PUT, OPTIONS Content-Type: application/json Vary: Accept [ { "non_field_errors": [ "Expected a list of items but got type \"dict\"." ] }, { "non_field_errors": [ "Expected a list of items but got type \"dict\"." ] } ] Here is the JSON I'm passing through the django rest framework API template: [ { "id": "1", "order": "5" }, { "id": "2", "order": "3" } ] Here is a view of my model: class Waitlist(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50, blank=True) identification = models.CharField(max_length=50) email = models.EmailField(max_length=100, validators=[], blank=True) mobile_phone = PhoneNumberField(blank=True) store_number = models.PositiveSmallIntegerField() order = models.PositiveSmallIntegerField() status = models.PositiveSmallIntegerField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.first_name + ' ' + self.last_name Here is a stripped down view of my views.py: from django.shortcuts import render, get_object_or_404 from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework import status from .models import Waitlist from .serializers import WaitlistOrderSerializer, WaitlistOrderListSerializer @api_view(['PUT']) def … -
Django: Is possible use _set into the filter() method?
I'm working on my ListView called IndexView on my polls app. This view currently return the last five published questions (not including those set to be published in the future). But my view also publish Questions that don't have any Choice, so I also want this view to only publish Questions that have Choices. IndexView in views.py class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """ Return the last five published questions (not including those set to be published in the future). """ return Question.objects.filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:5] Question and Choice models in models.py class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text My approach is to use the _set object and checking if the size of the queryset is bigger than 0 but I don't know if is possible use this object into the filter() method. -
AttributeError at / 'int' object has no attribute 'get'
Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/utils/deprecation.py", line 138, in call response = self.process_response(request, response) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/middleware/clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: AttributeError: 'int' object has no attribute 'get' Here is my code, #views.py class BookList(generic.View): model = Book def get(self, request, *args, **kwargs): books = Book.objects.all() if request.GET.get('Add') == 'Add': query = request.GET.get('hidden-book') book = Book.objects.filter(pk=query).update(moved=True) return book context = {'books': books} return render(request, 'main.html', context) #main.html <form method="GET" action=""> <input type="hidden" name="hidden-book" value="{{ book.id }}/> <input type="submit" name="Add" value="Add"/> </form> #models.py class Book(models.Model): moved = models.BooleanField(default=False) When the user presses the 'Add' input button, it should change the moved attribute in book to True. For background, I have an application that has a list of books, each with their own add button, that upon clicking an add button, the book is added to another list of books. My code works, but when I click the add button an AttributeError at / 'int' object has no attribute 'get' is raised. When I go back to 127.0.0.1:8000/, the book has been moved from the first to second list. Since I don't know what's causing the error, I … -
Trying to have django admin display all the files in a ticket
I am currently trying to have my admin item display page show all the files in the ticket, but for some reason it only shows the first file in a ticket. My model file is like so class Ticket(models.Model): OPEN = 'Open' CLOSED = 'Closed' STATUS_CHOICES = ( (OPEN, OPEN), (CLOSED, CLOSED), ) title = models.CharField(max_length=250) body = models.TextField() user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, blank=True) status = models.CharField(max_length=20, default=OPEN, choices=STATUS_CHOICES) uuid = models.CharField(max_length=250, default=Utils.generate_uuid) created_at = models.DateTimeField(default=timezone.now) email = models.CharField(max_length=200, null=True, blank=True) class TicketComment(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) body = models.TextField() user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, blank=True) uuid = models.CharField(max_length=250, default=Utils.generate_uuid) created_at = models.DateTimeField(default=timezone.now) def upload_path(instance, filename): ext = filename.split('.')[-1] name = filename.split('.')[0] if not instance.pk: unique_id = Utils.generate_hex_uuid() uploaddirectory = "static/uploads/%s/" % unique_id os.mkdir(uploaddirectory) return '{}/{}.{}'.format(uploaddirectory, name, ext) class TicketFile(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE, null=True, blank=True) ticket_comment = models.ForeignKey(TicketComment, on_delete=models.CASCADE, null=True, blank=True) inputfile = models.FileField(max_length=254, upload_to=upload_path, null=True, blank=True) inputfilepath = models.TextField(null=True, blank=True) name = models.TextField(null=True, blank=True) uuid = models.TextField(default=Utils.generate_hex_uuid) created_at = models.DateTimeField(default=timezone.now) Then my admin file looks like so from tickets.models.ticket import Ticket from tickets.models.ticket_comment import TicketComment from tickets.models.ticket_file import TicketFile from django.contrib import admin class TicketFileInline(admin.StackedInline): model = TicketFile extra = 0 class TicketCommentInline(admin.StackedInline): model = TicketComment extra … -
Please what should I do?
Here is the traceback, I need help please Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.14 Python Version: 3.10.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'publications', 'django_extensions', 'corsheaders', 'users', 'api', 'thumbnails', 'rest_framework.authtoken', 'dj_rest_auth', 'dj_rest_auth.registration', 'auth.tasks', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.apple', 'huey.contrib.djhuey', 'django_filters'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'corsheaders.middleware.CorsMiddleware'] Traceback (most recent call last): File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\deprecation.py", line 116, in call response = self.process_request(request) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\middleware\cache.py", line 145, in process_request cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\cache.py", line 362, in get_cache_key headerlist = cache.get(cache_key) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\cache.py", line 91, in get value = self._get(key, default, version, client) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\cache.py", line 31, in _decorator return method(self, *args, **kwargs) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\cache.py", line 98, in _get return self.client.get(key, default=default, version=version, client=client) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\client\default.py", line 253, in get client = self.get_client(write=False) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\client\default.py", line 105, in get_client self._clients[index] = self.connect(index) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\client\default.py", line 118, in connect return self.connection_factory.connect(self._server[index]) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\pool.py", line 72, in connect connection = self.get_connection(params) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\pool.py", line 91, in get_connection pool = self.get_or_create_connection_pool(params) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\pool.py", line 112, in get_or_create_connection_pool self._pools[key] = self.get_connection_pool(params) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\pool.py", line 125, in get_connection_pool pool = self.pool_cls.from_url(**cp_params) … -
Running Django Server
I need help tried to run server for Django and got this error, The included URLconf '<module 'myapp.urls' from 'C:\Users\user\Documents\Django Tutorial\myproject\myapp\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. for urls.py in myproject is: ` from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ]` for myapp views.py is: from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse('hello') For myapp urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] -
In Django, when trying to access a model's 1:1 relation that doesn't exist, sometime that relation is None, and sometimes it raises an exception. Why?
I noticed while debugging a Django application that with two tables with a 1:1 relation, trying to access the related object from the table that defines the 1:1 relation would return None, while trying to access the same nonexistent relation from the table that does not define the relation Django will raise a Model1.model2.RelatedObjectDoesNotExist exception. I was confused by this behavior as the same action has two different results on objects on the same type of relation. This is an example of the models used: class RelatedModel(models.Model): pass class RelationshipDefiner(models.Model): related_object = models.OneToOneField( RelatedModel, on_delete=models.CASCADE, related_name="relationship_definer", blank=True, null=True ) This is an example of trying to print the relations to screen: relationship_definer = RelationshipDefiner.objects.create() related_object = RelatedModel.objects.create() print("RELATIONSHIP DEFINER'S RELATED OBJECT:") print(relationship_definer.related_object) print("RELATED OBJECT'S RELATIONSHIP DEFINER:") print(related_object.relationship_definer) And the output: RELATIONSHIP DEFINER'S RELATED OBJECT: None RELATED OBJECT'S RELATIONSHIP DEFINER: Internal Server Error: /test/ File "/django/app/views/test.py", line 17, in test print(related_object.relationship_definer) app.models.sample.RelatedModel.relationship_definer.RelatedObjectDoesNotExist: RelatedModel has no relationship_definer. Why do 1:1 nullable relationships behave differently on either side of the relation, and is there a way to coerce Django to behave consistently across both sides of the relationship? -
Styling a GeoDjango widget with TailwindCSS
I have been trying to style the GeoDjango OSMWidget (for Polygon drawing) for ages but can't work out how to make it flexible. Setting the map width and map height is all fine for a fixed page size but what happens if someone snaps their browser window to half-screen? A fixed map width does not react to these changes and becomes an unwieldily feature so fast it's painful. Here is what the GeoDjango documentation suggests for widget styling: widgets = { 'geometry': forms.OSMWidget(attrs={ 'map_width': 1000, 'map_height': 400, 'default_zoom': 7.5 }), } Other widgets, such as forms.Select have the option for a style attribute where custom css can be defined. The map widgets ignore this completely. How can I force this map widget to respond to my css demands? I want flexible widgets, goddamit! *Bonus points for integration with tailwind -
How to automatically connect a logged in User to submit a document
Please I am new to coding, I am currently working on an app where there are various users trying to submit a document, I want them to be able to view only the documents they upload, while the admin can view all the users' documents. I was able to accomplish this but in this case the user field is a foreign key at the backend, and it's showing a drop down on the front end, I want each user to be automatically assigned to theirs, please how do I accomplish this. This is the model.py class Report(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) name = models.ForeignKey(Staff, null=True, on_delete=models.SET_NULL) reportname = models.CharField(max_length=200, null=True) date = models.DateTimeField(auto_now_add=True, null=True) report=models.FileField(upload_to='pdf/') def __str__(self): return self.reportname the view.py @login_required(login_url='loginpage') def report (request): if request.method == 'POST': form = ReportForm(request.POST, request.FILES) if form.is_valid(): form.user = request.user form.save() # Redirect to the document list after POST messages.info(request,'Submitted Sucessfully') return redirect('submitted_report') else: form = ReportForm() # A empty, unbound form return render(request,'report.html',{ 'form':form,'repor':report } ) @login_required(login_url='loginpage') def submitted_report(request): report = Report.objects.filter(user=request.user) return render(request,'submitted_report.html',{ 'report': report }) -
Django, TemplateSyntaxError at. Help me
I am doing a website by Django, but I have a registor problem, which I don't know how to solve,help me).Before last change, everything was working, but I have changed only this files: views.py from django.http import HttpResponse, HttpResponseRedirect, HttpResponsePermanentRedirect from django.shortcuts import render from django.http import * from django.template.response import TemplateResponse def index(request): cat = ["Cars", "Plates", "Fruits", "Phones", "Bananas"] return render(request, "firstapp/index.html", context={"cat": cat}) def about(request): return HttpResponse("About") def contact(request): return HttpResponseRedirect("/about") def details(request): return HttpResponsePermanentRedirect("/") index.html {% extends "firstapp/base.html" %} {% block title %}Index{% endblock title %} {% block header %}Main page{% endblock header %} {% block content%) <p>Types of products</p> {% for i in cat %} <li>{{ i }}</li> {% endfor %} {% endblock content %} and I got this problem: Invalid block tag on line 9: 'endblock'. Did you forget to register or load this tag? 1 {% extends "firstapp/base.html" %} 2 {% block title %}Index{% endblock title %} 3 {% block header %}Main page{% endblock header %} 4 {% block content%) 5 <p>Types of products</p> 6 {% for i in cat %} 7 <li>{{ i }}</li> 8 {% endfor %} 9 {% endblock content %} I don't know what to do in this case, … -
Error passing jinga url template to javascript function
I am trying to run the following javascript function <script> function getForm(id, element, url_route) { console.log(id, element, url_route) } </script> within <a href="javascript:void(0)" onclick="getForm('login-form', 'login-authentication', '{% url 'accounts:password_reset' %}');">Login</a> Clearly there is a problem with the quotations in '{% url 'accounts:password_reset' %}'. I have tried various different approaches to escape the quotations but the webserver still throws out an error. I have tried the following but still unsuccessful: <a href="javascript:void(0)" onclick="getForm('login-form', 'login-authentication', '{% url \'accounts:password_reset\' %}');">Login</a> <a href="javascript:void(0)" onclick="getForm('login-form', 'login-authentication', '{% url &quot;accounts:password_reset&quot; %}');">Login</a> I have also tried to build the url directly from the javascript function but it also doesn't work. var url = 'accounts:password_reset'; console.log('{% url "' + url + '" %}'); -
Pass capitalised variables to django settings.configure()
I am looking for a way to read from a list of variables and set them in Django settings using the settings.configure() method: from django.conf import settings def func(i): # do something and return for item in items: settings.configure(item=func(item)) But have no idea how I could write this properly to get past the TypeError: Setting 'item' must be uppercase. -
How to indicate required fields on initial form render, using Bootstrap 5 styling and Django?
I am using Django 4.1 and Bootstrap 5. I think I'd like to mark required fields in a form as required, or maybe optional fields as optional, as suggested in this question. Django/Bootstrap already styles fields as green/red after form submission, if a required field is missing, but my request is when the form is first rendered. Could be with *s or with "(optional)" or whatever. What's the best way to do it? -
CrispyError at /account/register |as_crispy_field got passed an invalid or inexistent field
I need help to fix this. Error during template rendering In template /*/dev/ecommerce/account/templates/account/registration/register.html, error at line 45 |as_crispy_field got passed an invalid or inexistent field 35 36 <h5> Purchase your favourite items today! </h5> 37 38 <hr> 39 <br> 40 41 <form method="POST" autocomplete="off"> 42 43 {% csrf_token %} 44 45 {{form.username|as_crispy_field}} 46 47 <br> <br> 48 49 50 {{form.email|as_crispy_field}} 51 52 <br> <br> 53 54 55 {{form.password1|as_crispy_field}} -
Get Session for Forms in Django
I'm working on a single page to handle all stufs related to accounts such as login/register. For that i'm using a CBV with a multiforms.py that do the get,post,validations etc. I'm having a problem with the login form, that is saying 'LoginForm' object has no attribute 'session' current error Here are the multiforms.py `class ProcessMultipleFormsView(ProcessFormView): def get(self, request, *args, **kwargs): form_classes = self.get_form_classes() forms = self.get_forms(form_classes) return self.render_to_response(self.get_context_data(forms=forms)) def post(self, request, *args, **kwargs): form_classes = self.get_form_classes() form_name = request.POST.get('action') if self._individual_exists(form_name): return self._process_individual_form(form_name, form_classes) elif self._group_exists(form_name): return self._process_grouped_forms(form_name,form_classes) else: return self._process_all_forms(form_classes) def _individual_exists(self, form_name): return form_name in self.form_classes def _group_exists(self, group_name): return group_name in self.grouped_forms def _process_individual_form(self, form_name, form_classes): forms = self.get_forms(form_classes, (form_name,)) form = forms.get(form_name) if not form: return HttpResponseForbidden() elif form.is_valid(): return self.forms_valid(forms, form_name) else: return self.forms_invalid(forms)` my LoginForm ` class LoginForm(MultipleForm,forms.Form): email = forms.EmailField(max_length = 60) password = forms.CharField(widget=forms.PasswordInput())` and the views.py ` def login_valid(self,request): user = authenticate(email=request.data.get('email'),password=request.data.get('password')) if user is not None: login(request,user) return HttpResponseRedirect(self.get_success_url('login')) else: return render(request,'accounts/login.html')` i already tried alot stufs but still dont get why this error is happening -
ModelForm saving value of submit button to database
I have a form in my project that just wouldnt grab whatever the user typed in and im stumped for why no matter what i typed into the input field, the string 'Post' is what gets saved into the database, which is the value of the submit button, nd whatever i changed the value to is also what gets saved. model class Post(models.Model): post = models.TextField(max_length=250) author = models.CharField(max_length=64) date_time = models.DateTimeField(default=timezone.now, blank=True) def __str__(self): return f"{self.author}, {self.date_time}, {self.post}" form class NewPostForm(ModelForm): class Meta: model = Post fields = ['post'] views.py def index(request): newpostform = NewPostForm() if request.user.is_authenticated: username = request.user.get_username() if request.method == 'POST': post = Post(author=username) newpostform = NewPostForm(request.POST,request.FILES, instance=post) if newpostform.is_valid(): post = newpostform.save() return render(request, "network/index.html") return render(request, "network/index.html", { "newpostform": newpostform }) html > <form action="{% url 'index' %}" method="post"> > {% csrf_token %} > <div> > {{ newpostform }} > </div> > <input id='post-btn' class="btn btn-primary" name="post" type="submit" value="Post"> > </form> -
How to get task status from django-celery-results using task id?
I want to implement celery on a django app. I have used django_celery_results to store task results. celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "coutoEditor.settings") app = Celery("coutoEditor") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() settings.py CELERY_BROKER_URL = "redis://localhost:6379" CELERY_RESULT_BACKEND = "django-db" CELERY_RESULT_EXTENDED = True tasks.py @shared_task() def speed_up_vid_task(input_path, speed_factor, start, end): ''' Method Params: input_path: The video file url or directory path file name speed_factor: The factor for the speed up process start: start of the video part that needs to be sped up (in secs) end: end of the video part that needs to be sped up (in secs) ''' start = convert_to_sec(start) end = convert_to_sec(end) filename = str(uuid.uuid4()) print(filename, "new") temporary_dir = BASE_DIR + '/' + editor_speedUp_temp_dir # editor_temp_dir = media/editor/speed_vid/temp/" output_dir = BASE_DIR + '/' + editor_speedUp_output_dir # editor_speedUp_output_dir = media/editor/speed_vid/ # Check for broken url r = requests.get(input_path, stream=True) if not r.status_code == 200: return Response({ 'message': "media file is corrupted", 'data': "broken url process could not be completed", 'status': False }, status=status.HTTP_400_BAD_REQUEST) if not os.path.exists(output_dir): os.mkdir(output_dir) if not os.path.exists(temporary_dir): os.mkdir(temporary_dir) stream = os.popen( "ffmpeg.ffprobe -loglevel error -select_streams a -show_entries stream=codec_type -of csv=p=0 '{}'".format( input_path)) output = stream.read() if len(output) == 0: input_path_vid = os.path.join(BASE_DIR, temporary_dir) + filename … -
CSRF verification Failed in Firebase and Django integration
I am trying to integrate django and DRF with firebase real-time database and while creating a post request I ran into a CSRF verification error. CSRF verification failed. Request aborted. Some solutions I found online said that I should use render but I am actually using Django Rest Framework and would like to use something that works with JsonResponse and Serializers. Here's a test code. def post(self, request): """Function to handle post requests Args: request (_type_): _description_ """ # Get the data to be posted from the request name = request.POST.get('name') age = request.POST.get('age') location = request.POST.get('location') # Set the reference to the database ref = db.reference('/user1') # Push the data to the database ref.push({ 'Name': name, 'Age': age, 'Location': location }) Let me know if I should share how I am creating my firebase client, although I don't think that would be necessary. In conclusion, I would like to find a way to add a csrf_token to a post request method in Django and DRF. Another solution I saw used csrf_exempt but I don't want to use that either as that is not ideal. I do plan on taking this to production at some point so do recommend solutions … -
How to modify objects in django ListView?
I have a ListView for a blog with fields of "title" and "text". How to change "text" for example I want to summarize it something like text[:100] I don't want to change the database. I think the solution is modifying get_queryset but don't know how to implement it. -
Docker-Compose Network Issue on Ubuntu 22.04 LTS
I've been developing my python application using Django with PostgreSQL and Nginx and Docker, driven by Docker-Compose on my Macbook M1. And recently, decided to deploy it on the remote server, which has Ubuntu 22.04 LTS, but encountered really weird issue. My web application says, that it cannot resolve host postgresql (service at docker-compose file, which you can find down below), however, it works fine on my machine, can it be related to the Docker? It might be because I installed imcompatible versions of Docker and Docker-compose on this remote server or apparently used wrong commands, but not really sure about that, as I haven't gained enough experience of working with Ubuntu yet. My Macbook's M1 Docker & Docker-compose Versions: ~ Docker - 20.10.12 ~ Docker-Compose - 1.29.2 My Remote's Server Ubuntu Docker & Docker-compose Versions: ~ Docker - 20.10.23 ~ Docker-compose - 1.29.2 My docker-compose.yaml file version: "3.9" services: nginx_server: container_name: "nginx_web_server" image: crazycoderrr/vdnh_nginx_server:latest # образ nginx для нашего проекта ports: - "8010:80" depends_on: - application_service volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf networks: - private_network application_service: container_name: "application_server" image: crazycoderrr/vdnh_application:latest # образ backend сервиса нашего приложения ports: - "8000:8000" depends_on: - postgresql env_file: ./env/application.env networks: - private_network postgresql: container_name: "postgresql_database" image: crazycoderrr/vdnh_postgres_db:latest … -
How to override the autocomplete view for a specific model field in the Django admin?
I need to override the way a Select2 widget of a particular ForeignKey is behaving in the Django (4.1) admin. Namely, I am trying to increase the number of objects returned by the AJAX requests and defined by paginate_by in AutocompleteJsonView. Sadly this great solution no longer works with Django 4. How can I extend AutocompleteJsonView and somehow tell Django to use my custom view?