Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to send variable from JS to Python using queryparameter
I want to pass a variable using Ajax from a JS function to a python function in my Django project. I am able to call the python function. Using the ajax method, I know this because the print function in the python function runs. However I want pass my variable through this ajax call. it is being sent as a queryparameter. however the result that is printed is just: "Variable: local" and not the actual variable details. How can i fix this? JS function calling (){ var local = 25 $.ajax({ type:'GET', url:'printsome/?variable=local', success: function(response){ console.log('success'); console.log(local); }, error: function (response){ console.log('error'); } }); PY from django.http import JsonResponse def print_some(request, ): variable = request.GET.get('variable', 'default') print('Variable:', variable) return JsonResponse({}) -
Django Form Wizard not saving FileField
I have a 5 step form wizard, each their own form. I have a FileField in the first, but something is going wrong. When I reach the final step and press submit, my model gets saved but the file field is empty in my database. It's not "null", but actually empty. I created the "file_storage" variable but that only stores the file temporarily, it get's deleted as soon as I submit the form this is my wizard class: import json import logging import os import keyboard from django.conf import settings from django.core.files.storage import FileSystemStorage from django.core.mail import EmailMessage from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from formtools.wizard.views import SessionWizardView from .forms import * logger = logging.getLogger('django') FORMS = [ ("company", CompanyForm), ("addresses", AddressesForm), ("references", ReferenceFormSet), ("contacts", ContactFormSet), ("payment", PaymentForm), ] TEMPLATES = { "company": "form/step-1.html", "addresses": "form/step-2.html", "references": "form/step-3.html", "contacts": "form/step-4.html", "payment": "form/step-5.html", } form_data = [] form_data2 = {} class RegisterWizard(SessionWizardView): file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'temp')) def get_context_data(self, form, **kwargs): context = super().get_context_data(form=form, **kwargs) context.update({'callme_forms': CallMeForms(prefix='callme')}) return context @property def first_step_files(self): return self.storage.get_step_files(self.steps.first) def process_step(self, form): data = {} form_data.extend(self.get_form_step_data(form)) for attr, value in self.get_form_step_data(form).items(): if 'reference' not in attr: if 'company-' in attr: attr = attr.replace('company-', '') … -
Django: how to include missing pk field into serializer when updating nested object?
I have a serializer in my Django app that is meant for updating a nested object. Updating works, but I'm facing another problem: I can't delete objects that are not in validated_data['events] because I don't have the id to be compared with my instance id's. For reference, these are my Models: class Plan(models.Model): planId = models.CharField(primary_key=True, max_length=100, unique=True) name = models.CharField(max_length=200) class PlanEvent(models.Model): plan = models.ForeignKey(Plan, on_delete=models.CASCADE) id = models.CharField(primary_key=True, max_length=100, unique=True, blank=False, null=False) done = models.BooleanField() title = models.CharField(max_length=100, blank=True) This is my PlanEventUpdateSerializer: class PlanEventUpdateSerializer(serializers.ModelSerializer): class Meta: model = PlanEvent fields = ('done', 'title') Is there some way to include the id, so I could compare the id's like this in my update method: class PlanUpdateSerializer(serializers.ModelSerializer): events = PlanEventUpdateSerializer(many=True) class Meta: model = Plan fields = ('name',) .... def update(self, instance, validated_data): events_validated_data = validated_data.pop('events') events = (instance.events.all()) events = list(events) event_ids = [item['id'] for item in events_validated_data] for event in events: if event.id not in event_ids: event.delete() -
Django Error - Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable?
When I first ran the server everything was fine and the project was running properly. But after few days when I ran the server again, it gave me an error Traceback (most recent call last): File "C:\Users\Admin\Desktop\Django Project\first\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Admin\Desktop\Django Project\first\manage.py", line 22, in <module> main() File "C:\Users\Admin\Desktop\Django Project\first\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? To be specific, I'm on Windows 10, using VS Code as my IDE (I've not setup any virtual environment). Django version installed - 3.2.9 Python version installed - 3.10.0 PIP version installed - 21.2.3 Here is a screenshot of my Environment Variables [ -
Django test a view return 302 insteatd of 200
I am writting some tests in a Django project. For example, I want to test an index view in one app fo my Django project. But I am not sure test code below is correct, event if test passed. User need to be authentified to access this index view. So, in SetUp, I first create test user and logged in. And finally, I test I can get index view by testing status_code return. But if I omit follow=True, it return 302 and test failed. Is my test code correct? class IndexPageTestCase(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create_superuser(username='test', password='test', email='test@test.fr') self.client.login(username='test', password='test') def test_index_page(self): response = self.client.get(reverse('ecrf:index'), follow=True) self.assertEqual(response.status_code, 200) Django project architecture - core - urls.py - ecrf - urls.py - views.py core/urls.py urlpatterns = [ path('ecrf/', include('ecrf.urls')), ] ecrf/urls.py urlpatterns = [ path("", views.index, name="index"), ] ecrf/views.py @login_required def index(request): ... return render(request, "ecrf/index.html", context) -
How to process webcam frames in django views using opencv
I want to have a django view with python code which uses opencv like... cap = cv2.VideoCapture(0) while(True): ret, image = cap.read() if ret == False: break result = <Some opencv processing > if <condition1>: return render(request, 'myapp/dashboard.html', context={"welcome": 'Error1'}) if <condition2>: return render(request, 'myapp/dashboard.html', context={"welcome": 'Error2'}) elif <condition3>: return render(request, 'myapp/dashboard.html', context={"welcome": 'Error3'}) else: return render(request, 'myapp/dashboard.html', context={"welcome": 'Welcome to dashboard'}) if cv2.waitKey(1) & 0xFF == ord('q'): break I want while loop running continuously and then based on if else conditions make changes in template using context. Is there a simple way to do this without using gen() for capturing frames and then processing them. -
Errors deploying my web application with elastic beanstalk and django
First time using aws and elastic beanstalk. My Django site works fine when I host it locally. I've followed the instruction on deploying a Django application using eb on the aws guide. I think my issues are related to my virtual environment. Can someone take a look at these screenshots and see if there are any obvious issues I am missing? command line pycharm elastic beanstalk errors -
Compress to zip file and add a password
I compress the csv file and returned the zipped file as follows in a Django project def get_csv_file(request): response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="member.zip"' users = User.objects.all() file_path = os.path.join(tempfile.gettempdir(), 'member.csv') f = open(file_path, 'w') file_writer = csv.writer(f, quotechar='"', quoting=csv.QUOTE_MINIMAL) for user in users: file_writer.writerow([user.username, user.email]) f.close() z = zipfile.ZipFile(response, 'w') z.write(file_path) z.close() return response Is there any way to add a password protection to the files? I tried with pyminizip but dont know how to return it as a response object -
Make calculations for records inside pagination, django
I want to calculate the sum of two records but only inside the pagination. class MacaListView(ListView): model = Maca paginate_by = 20 def get_context_data(self, *, object_list=None, **kwargs): context = super(MacaListView, self).get_context_data(object_list=None, **kwargs) maca = Maca.objects.all() for i in range(0, maca.count()): maca = Maca.objects.get(maca[i].id) maca.number = maca.number + 1 maca.save() This will go to every single record and do the logic. I want the logic to be executed for only records in pagination (do calculate for only 20 records) -
import sqlparse ModuleNotFoundError: No module named 'sqlparse'
I have installed pip install sqlparse pip3 install sqlparse conda install sqlparse But still getting sqlparse module Why is that? -
JQuery Tablesorter: How to add changing icons to table column headers?
I'm trying to create a weather data website as my first project using django and bootstrap. Wanting to implement table sorting to sort the weather data table I happened upon this JQuery Tablesorter. I have implemented the sorting feature but how do I add the sorting icons to my column headers and have them change based on how the column is sorted? I have little to no experience with JavaScript. -
How to trim whitespaces from inside of string with min_length and max_length validation?
How to trim whitespace from inside of string with min_length and max_length validation? name = serializers.CharField(min_length=18, max_length=18, trim_whitespace=True, allow_blank=True, allow_null=True, required=False) test_string_that_should_be_invalid = "1111111111111111 1" test_string_valid = "111111111111111111" -
Can't access django url (page not found)
I have models like this : class Region(models.Model): region_parent = models.ForeignKey( "self", blank=True, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=255) title = models.CharField(max_length=255) description = RichTextField() description_on_list = RichTextField(blank=True) thumbnail = models.ImageField( upload_to="thumbnail-region", blank=True, max_length=255) sidebar = RichTextField(blank=True) ad_manager = models.TextField(blank=True) meta_keywords = models.TextField(blank=True) logo_on_navbar = models.ImageField( upload_to="logo-on-navbar/", blank=True, max_length=255) display_on_navbar = models.BooleanField(default=True) slug = models.SlugField(unique=True) def get_absolute_url(self): if self.region_parent is not None: return reverse('vineyards:region', kwargs={'parent': self.region_parent.slug, 'region': self.slug}) else: return reverse('vineyards:region-without-parent', kwargs={'region': self.slug}) class Vineyard(models.Model): name = models.CharField(max_length=255) text = RichTextField() rating = models.FloatField() custom_overlay = models.ImageField( upload_to="custom-rating/", blank=True, max_length=255) google_map = models.TextField() wine_rg_url = models.URLField(blank=True) wine_rg = models.CharField(max_length=255) wines_url = models.URLField(blank=True) wines = models.CharField(max_length=255) size = models.CharField(max_length=255) grapes = models.CharField(max_length=255) owner_url = models.URLField(blank=True) owner = models.CharField(max_length=255) visits = models.CharField(max_length=255) region = models.ForeignKey(Region, on_delete=models.CASCADE) regions = models.ManyToManyField( Region, blank=True, related_name="regions") cover = models.ImageField(upload_to="vineyard/", max_length=255) sidebar = RichTextField(blank=True) ad_manager = models.TextField(blank=True) meta_keywords = models.TextField(blank=True) top_slider = models.BooleanField(default=False) cover_slider = models.BooleanField(default=False) hide_rating = models.BooleanField(default=False) slug = models.SlugField(unique=True) def get_absolute_url(self): if self.region.region_parent is not None: return reverse('vineyards:detail', kwargs={'parent': self.region.region_parent.slug, 'region': self.region.slug, 'slug': self.slug}) else: return reverse('vineyards:detail-without-parent', kwargs={'region': self.region.slug, 'slug': self.slug}) And this is my urls.py: app_name = 'vineyards' urlpatterns = [ path('<str:parent>/<str:region>/<slug:slug>/form/', rr_form, name="detail-form"), path('<str:region>/<slug:slug>/form/', rr_form, name="detail-without-parent-form"), path('<str:parent>/<str:region>/', vineyard_region, name="region"), path('<str:region>/', vineyard_region, name="region-without-parent"), path('<str:parent>/<str:region>/<slug:slug>/', … -
Passing a variable to python using Ajax method
I want to pass a variable using Ajax from a JS function to a python function in my Django project. I am able to call the python function. Using the ajax method, I know this because the print function in the python function runs. However how to I pass my variable through this ajax call? I just want to pass the local variable so it can be printed by the python function. JS function calling (){ var local = 25 $.ajax({ type:'GET', url:'printsome/', success: function(response){ console.log('success'); console.log(local); }, error: function (response){ console.log('error'); } }); } python def print_some(request): from django.http import JsonResponse print('this python function was called') return JsonResponse({}) -
Django : Page Not Found when trying to access static files
I know there are already several threads on the topic. I've been through most of them (especially all the troubleshooting listed in this one) but I can't figure out my issue. I am trying to use a Bootstrap template in my Django project, and I'd like to simply start by accessing the files in the /static/ directory. My project directory looks like this : Whenever I try to load the page http://localhost:8000/static/theme/assets/css/style.css it returns a Page not found error (and obviously no CSS/JS content appears on my index). Here are my settings: I have debug = True ÌNSTALLED_APPS contains django.contrib.staticfiles settings.py looks like this : STATIC_URL = "/static/" STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),) But I still can't access anything from the /static/ directory. I tried to access the CSS and JS files in base.html this way : {% load static %} ... <link href="{% static 'theme/assets/css/style.css' %}" rel="stylesheet"> I really have no clue how I could solve this. Thanks in advance for your help ! -
if am searching something iam getting the result from post but when i press next button it is going to get function to get data
#here when i search button iam getting data i want from post but when i used pagination to go to the next page it is again visiting to get function pls help me to class CrawlMonitorOverall(View): ELEMENTS_PER_PAGE = 1 def get(self, request: HttpRequest) -> HttpResponse: print("get") print(request) form = SearchButtonForm() execution_queryset = CrawlRuleExecutionModel.objects.all().order_by('-id') context_data = self._get_execution_data(request, execution_queryset, form) return render(request, 'crawl_monitoring/overall_view.html', context_data) def post(self, request: HttpRequest) -> HttpResponse: print("post") form = SearchButtonForm(request.POST) if form.is_valid(): execution_queryset = self._get_execution_queryset(form) context_data = self._get_execution_data(request, execution_queryset, form) return render(request, 'crawl_monitoring/overall_view.html', context_data) def _get_execution_queryset(self, form: SearchButtonForm) -> QueryType[CrawlRuleExecutionModel]: print(1) crawl_execution_name = form.cleaned_data["crawl_execution_name"] if crawl_execution_name: execution_queryset = CrawlRuleExecutionModel.objects.filter( crawl_rule__name__contains=crawl_execution_name).order_by('-id') else: execution_queryset = CrawlRuleExecutionModel.objects.all().order_by('-id') return execution_queryset def _get_execution_data(self, request: HttpRequest, execution_queryset: QueryType[CrawlRuleExecutionModel], form) -> \ Dict[str, Union[Paginator, Any]]: print(2) paginated_data = self._get_paginated_data(request, execution_queryset) execution_data = GenCrawlMonitorOverallContext().get_context(paginated_data) print(execution_data) context_data = { "execution_data": execution_data, "form": form, "paginator": paginated_data } return context_data def _get_paginated_data(self, request, query_set: QueryType[CrawlRuleExecutionModel]) -> Page: print(3) paginator = Paginator(query_set, self.ELEMENTS_PER_PAGE) page_number = request.GET.get('page') paginated_data = paginator.get_page(page_number) return paginated_data -
Hello design option : React + Django
I need your help on a design best option please, I am working on an app, the front is using react and the back is on Django. This is more a general question on how one should think when designing models! Should I rely on my front representation or what I personally think better is to align to objects normalization and abstraction. Here as an example: Let's say you two objects Company and Investment. A company could have many investments but an investment is linked to only one company. So you would add a foreign key to investment and in API level you would be able to list investment by companies like this : /api/company/id/investments Now this will return a list of investments per company. Now in front side I have only one investment to display, because only one investment/company could be active at a time (business rule). Here is my question, if let's say I filter by active= True /api/company/1/investments/?active=True I will get an array but this array will be always holding one investment. Is this a good design? Is there a way to force django to make an API filter response a json object instead of an array? … -
a technique for live updates other than firebase push notification fro my mobile flutter app
I was using the fcm push notification to get the real time updates(the update in my device,ie. whether the lights are manually off or on in the device etc..)get happen in the mobile application.But the push notifications are sometimes found missing and my app started showing sync issues to the real time. It could be very helpfull for me if anyone can suggest a better method to implement this process. I had heard about enabling a socket connection but dont know much about that. Thankyou -
Django Which model field to add an text editor when clicking on it?
I have my Django model and would like to add a text editor field. This text editor is representing like an Icon and when clicking on it, user must see it open and write any comment. I am not talking about django text input field where user can directly add comment in the form. I want something like that (in red circle). -
Why the login_requried decorator doesn't work after I log out from the account?
Working on a project using Django 3.2, I have been added new features to the project by adding a login/register page for the user. To do that, I used which I used this library provided by Django from django.contrib.auth.models import User, and as well in the views I used from django.contrib.auth import authenticate, login, logout library. After I finished the login/register successfully I decided to do the authenticate the home page for the reason that the user without an account can't have access to the home page. To do that I used the decorators from django.contrib.auth.decorators import login_required, and I used it on every view that I want to authenticate for the unregistered user. To understand it better will show the code below: views.py from django.http.response import HttpResponse from django.shortcuts import render, redirect from django.utils import timezone from django.db.models import Count from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.contrib import messages from .models import * from .models import __str__ from .forms import CreateUserForm # Create your views here. @login_required(login_url='login/') def home(request): count_item = todo.objects.count() all_items = todo.objects.all().order_by("created") context = {'all_items': all_items, 'count_item':count_item} return render(request, 'html/home.html', context) @login_required(login_url='login/') def … -
Django nested serializers not returning what I want
I'm relatively new to Django and I'm working on an application that has me scratching my head. I have two models defined as follows: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) name = models.CharField(_('name'), max_length=50, blank=False) surname = models.CharField(_('surname'), blank=True, max_length=50) phone_number = models.CharField(validators=[phone_validator], max_length=16, blank=True) class History(models.Model): hist_id = models.AutoField(primary_key=True) user = models.ForeignKey( User, on_delete=models.CASCADE ) timestamp = models.DateTimeField(auto_now=False, auto_now_add=False) actions = models.JSONField(default=dict) traces = models.JSONField(default=dict) I would like to obtain a list of all users, and for each user I want all the History objects as a list. Here is the View I've created: class HistoryQuery(ListAPIView): serializer_class = HistorySerializer def get_queryset(self): return User.objects.all() and here is the serializer that I'm trying to use: class HistorySerializer(serializers.Serializer): class HistorySummarySerializer(serializers.Serializer): class Meta: model = History fields = ['hist_id', 'user'] history = HistorySummarySerializer(many=True, read_only=True) class Meta: model = User fields = ['history'] With this setup, I'm getting an array with length equal to the number of users that I have in my database, but each of its elements is empty. I cannot figure out what I'm doing wrong, so any help is appreciated. Should I reverse my logic and query the History model instead? If it is relevant, there are around … -
How to reverse filter based on latest entry in Django
I have a customer table and customer order table as below class Customer(models.Model): name = models.CharField() class CustomerOder(models.Model): customer = models.ForiengKey(Customer) item = models.CharField() datetime_of_purchase = models.DateField() Sample database entry Table: Customer id name 1 A 2 B 3 C Table: CustomerOder id customer item datetime_of_purchase 1 A item_3 2021-11-10 10:00:00 2 A item_2 2021-11-11 10:00:00 3 B item_1 2021-11-11 10:00:00 4 A item_1 2021-11-12 10:00:00 5 B item_2 2021-11-12 10:00:00 6 C item_1 2021-11-13 10:00:00 Suppose i need to filter customer whose latest purchase is 'items_1' so the sample after filtering should get only Customer 'A' and 'C' whose latest purchase is 'item_1' Sample: <QuerySet [<Customer: A>, <Customer: C>]> -
Django Rest Framework NoReverseMatch not a valid view function or pattern name
First some context : Models class : class Property(models.Model, AbstractUsagesLinked, AbstractErrorsFinder, InsurableMixin): type = models.ForeignKey(PropertyType, verbose_name=_('type de lot'), null=True, blank=True, related_name='properties_set', on_delete=models.CASCADE) # other fields Serializers class : class PropertySerializer(serializers.HyperlinkedModelSerializer, FlexFieldsModelSerializer): type = serializers.HyperlinkedRelatedField(view_name="api:propertytype-detail", read_only=True) # add hyperlink reference # others fields class Meta: model = Property fields = [field.name for field in model._meta.fields] expandable_fields = { 'type': (PropertyTypeSerializer, {'many': False}), # others fields } class PropertyTypeSerializer(serializers.HyperlinkedModelSerializer, FlexFieldsModelSerializer): class Meta: model = PropertyType fields = [field.name for field in model._meta.fields] Views class : @permission_classes((Check_API_KEY_Auth, )) class PropertyDetail(RetrieveAPIView): queryset = Property.objects.all() serializer_class = PropertySerializer pagination_class = CustomPagination @permission_classes((Check_API_KEY_Auth, )) class PropertyTypeDetail(RetrieveAPIView): queryset = PropertyType.objects.all() serializer_class = PropertyTypeSerializer pagination_class = CustomPagination Urls : api.urls.py : urlpatterns = [ # lots of path path('property/', views.PropertyList.as_view(), name="property-list"), path('property/<int:pk>/', views.PropertyDetail.as_view(), name="property-detail"), path('propertytype/', views.PropertyTypeList.as_view(), name="propertytype-list"), path('propertytype/<int:pk>/', views.PropertyTypeDetail.as_view(), name="propertytype-detail"), main.urls.py : urlpatterns = [ # lots of path url(r'^api/', include((api.urls, 'api'), namespace='api')), ] When i request property i get : django.urls.exceptions.NoReverseMatch: Reverse for 'propertytype-detail' not found. 'propertytype-detail' is not a valid view function or pattern name. django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "propertytype-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on … -
Populate single dropdown from two tables in django python sqlite
I am new to Django, Please provide me any method to do this. Thanx in Advance. -
Missing Django core translations
I am trying to translate django core strings which for my language are untranslated in the original .po file. When I add them to my own .po file and translate them, the system works fine. The problem comes every time I use the makemessages command, since the generator interprets that those text strings have been deleted and comments them in the .po file. Can I hand generate a file that contains the translations and is not affected by the makemessages command? On the other hand, is it possible to tell him not to comment on the deleted lines?