Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to give priority to a certain field in SearchFilter fields in django rest framework?
I have a simple search api which search the db based on the query parameter provided to the search keyboard. It works fine, but it has some issues. For example, I have a category named Tv and home appliances. It has products like LG speakers and led tv. I have search qeury parameters for both category name and product name. When I search tv, speaksers products are coming in the first page while tv products are coming in the 5th page which I dont want. It is because, category name has Tv and Home. What I want is tv prodcuts to be appear in the first page while speakers to the other pages. For this I have to prioritise the product name field rather than category name. How to do that?? { id:1 category: TV and Home, product: 1500 W Speakers } { id:2 category: Tv and Home, product: Led Tv 32" } I want id:2 to be appeared first then, the id:1, if I search with Tv. class PrdouctSearchAPIView(ListAPIView): permission_classes = [AllowAny] queryset = Product.objects.all() print(queryset) serializer_class = ProductSerializer filter_backends = [SearchFilter,OrderingFilter] search_fields = ['name','brand__name','collection__name','sub_category__name', 'description','variants__color','category__name'] pagination_class = CustomPagination My local endpoint is: http://127.0.0.1:8000/api/productsearch?search=tv My model: class Product(models.Model): merchant … -
Heroku run python manage.py makemigartions --app=<appname> is throwing ImproperlyConfigured: Set the DATABASE_NAME environment variable
I have pushed my django project to GitHub with this database setting for Postgres: import dj_database_url DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env("DATABASE_NAME"), 'USER': env("DATABASE_USER"), 'PASSWORD': env("DATABASE_PASSWORD"), 'HOST': env("DATABASE_HOST"), 'PORT': env("DATABASE_PORT"), } } DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) And then I have run git push heroku main. The build was successful. Then when I'm running heroku run python manage.py makemigrations --app=<app_name> it's throwing this error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 368, in execute self.check() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/app/.heroku/python/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/checks/caches.py", line 14, in check_default_cache_is_configured if DEFAULT_CACHE_ALIAS not in settings.CACHES: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked … -
use django send file
I want to send a request from client (axios send) to server, and server return a file, and client will accept (axios accept) this file, and use javascript to modify this file, and then show the file data on browser I think some thing wrong happened in file response. I have struggle this for a day. And, I am not familiar with django. I just learn it a little from web blog. vscode command show this error Exception happened during processing of request from ('127.0.0.1', 9453) Traceback (most recent call last): File "C:\Anaconda3\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Anaconda3\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\lib\wsgiref\handlers.py", line 266, in write "write() argument must be a bytes instance" AssertionError: write() argument must be a bytes instance During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\lib\wsgiref\handlers.py", line 141, in run self.handle_error() File "C:\lib\site-packages\django\core\servers\basehttp.py", line 123, in handle_error super().handle_error() File "C:\Anaconda3\lib\wsgiref\handlers.py", line 368, in handle_error self.finish_response() File "C:\Anaconda3\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Anaconda3\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Anaconda3\lib\wsgiref\handlers.py", line 331, in send_headers if not self.origin_server or self.client_is_modern(): File "C:\Anaconda3\lib\wsgiref\handlers.py", line 344, in client_is_modern return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9' TypeError: 'NoneType' object is … -
Direct assignment to the forward side of a many-to-many set is prohibited. Use croft.set() instead
class Balance(models.Model): croft = models.ForeignKey(Croft, on_delete=models.CASCADE, verbose_name='Участок') remains = models.DecimalField(max_digits=10, decimal_places=2, default=0, blank=True, null=True, verbose_name='Остаток') date_change = models.DateTimeField(auto_now=True, verbose_name='Дата изменения') def __str__(self): return self.croft.number @receiver(post_save, sender=Croft) def create_balance(sender, instance, created, **kwargs): if created: Balance.objects.create(croft=instance) class Meta: verbose_name = 'Баланс участка' verbose_name_plural = 'Балансы участков' ordering = ('id',) class Contributions(models.Model): TYPE_CHOICES = ( ('membership_fees', 'Членские взносы'), ('targeted_contributions', 'Целевые взносы') ) UNITS_CHOICES = ( ('m2', 'за кв.м.'), ('croft', 'за участок'), ('per_hundred', 'за сотку') ) name = models.CharField(max_length=120, verbose_name='Наименование') type_contribution = models.CharField(max_length=100, choices=TYPE_CHOICES, verbose_name='Вид взносов') croft = models.ManyToManyField(Balance, verbose_name='Участок') sum_contribution = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Размер взноса') units = models.CharField(max_length=100, choices=UNITS_CHOICES, verbose_name='ед. изм.') date_contribution = models.DateField(default='', verbose_name='Срок уплаты') all_crofts = models.BooleanField(default=True, verbose_name='Действует для всех участков') round_to_range = models.BooleanField(default=False, verbose_name='Округлять в большую сторону') def __str__(self): return self.name def save(self, *args, **kwargs): if not self.id: super(Contributions, self).save(*args, **kwargs) self.croft = self.croft self.croft.remains = self.croft.remains - (self.sum_contribution * self.croft.croft.area) self.croft.save() return super(Contributions, self).save(*args, **kwargs) class Meta: verbose_name = 'Начисление взносов' verbose_name_plural = 'Начисление взносов' -
Got an error creating the test database - django, docker, mysql
I have an issue with creating test database. I use mysql for db and docker compose. I have no problem running docker containers with docker-compose, but when I run test it spits this error message. Note that the name of django service is web, and mysql service is db. $ docker-compose run --rm web sh -c "python manage.py test" Creating sociallogin_web_run ... done Creating test database for alias 'default'... Got an error creating the test database: (1044, "Access denied for user 'myuser'@'%' to database 'test_mydb'") my docker-compose.yml: version: "3.9" services: db: image: mysql:8 env_file: - .env command: - --default-authentication-plugin=mysql_native_password restart: always # ports: # - "3306:3306" # volumes: # - data:/var/lib/mysql web: build: . command: > sh -c "python manage.py wait_for_db && python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" depends_on: - db env_file: - .env # volumes: # data: my .env file looks like this: MYSQL_ROOT_PASSWORD=rootpass MYSQL_USER=exampleuser MYSQL_PASSWORD=examplepass MYSQL_DATABASE=exampledb MYSQL_PORT=3306 SECRET_KEY=exmaple_random_characters DATABASES in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get('MYSQL_DATABASE'), 'USER': os.environ.get('MYSQL_USER'), 'PASSWORD': os.environ.get('MYSQL_PASSWORD'), 'PORT': os.environ.get('MYSQL_PORT'), 'HOST': 'db', 'TEST': { 'NAME': 'test_mydb', } } } I looked at this, and I even tried this. It didn't … -
How to solve the NOT NULL constraint failed Error in Django
I am getting an IntegrityError when I want to save a new course on my e-learning website. Of course, I have searched for a similar solution on StackOverflow but I couldn't find an appropriate way for my solution. here are my models UserAccount Model from django.db import models from django.contrib.auth.models import AbstractUser class UserAccount(AbstractUser): email = models.EmailField( max_length=255, verbose_name='email', unique=True) username = models.CharField(max_length=255, unique=True) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) Course Model from django.db import models from accounts.models import UserAccount class Course(models.Model): owner = models.ForeignKey( UserAccount, related_name='courses_created', on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField() description = models.TextField() cover_photo = models.ImageField(upload_to="cover/", null=True, blank=True) Also, my course form is here class CourseForm(forms.ModelForm): class Meta: model = Course fields = ['curriculum', 'title', 'description', 'cover_photo'] widgets = { 'description': forms.Textarea(attrs={'rows': 3}) } So in my view, I like to send the list of my courses to the template and also my CourseForm() using the get_context_data method. The code is bellow My class-based view class OwnerListMixin(object): def get_queryset(self): qs = super().get_queryset() return qs.filter(owner=self.request.user) class OwnerCourseMixin(OwnerListMixin, LoginRequiredMixin, PermissionRequiredMixin): model = Course fields = ['curriculum', 'title', 'description', 'cover_photo'] success_url = reverse_lazy('manage_course_list') class ManageCourseListView(OwnerCourseMixin, ListView): template_name = "courses_app/manage/course/list.html" permission_required = "courses_app.view_course" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] … -
What is the problem in this very simple views.py queryset?
I try to query a Course by its own field "name" instead of pk. And what should be the path when querying this? All basic Cruds and query by pk works fine with this code. Here I have all related files attached: models.py from django.db import models # Teacher = opettaja in Finnish class Opettaja(models.Model): nimi = models.CharField(max_length=100, default='') puhelin = models.CharField(max_length=20, default='') class Meta: ordering = ['nimi'] # Course = kurssi in Finnish class Kurssi(models.Model): nimi = models.CharField(max_length=100, default='') laajuus = models.IntegerField() opettaja = models.ForeignKey(Opettaja, on_delete=models.CASCADE) class Meta: ordering = ['nimi'] serializers.py from rest_framework import serializers from .models import Opettaja, Kurssi class OpettajaSerializer(serializers.ModelSerializer): class Meta: model = Opettaja fields = ['id', 'nimi', 'puhelin'] class KurssiSerializer(serializers.ModelSerializer): class Meta: model = Kurssi fields = ['id', 'nimi', 'laajuus', 'opettaja'] urls.py from django.urls import include,path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r"opettaja", views.OpettajaViewSet) router.register(r"kurssi", views.KurssiViewSet, "nimi") urlpatterns = [ path("api/", include((router.urls, "app"))), ] views.py from rest_framework import viewsets from .models import Opettaja, Kurssi from .serializers import OpettajaSerializer, KurssiSerializer class OpettajaViewSet(viewsets.ModelViewSet): queryset = Opettaja.objects.all() serializer_class = OpettajaSerializer class KurssiViewSet(viewsets.ModelViewSet): queryset = Kurssi.objects.all() serializer_class = KurssiSerializer def get_queryset(self): queryset = Kurssi.objects.all() nimi = self.request.query_params.get("nimi") if nimi is not None: nimi … -
Unable to make dynamic variables in views and url of DJANGO Rest Framework
I was trying create a api like "http://127.0.0.1:8000/api/data/year". but i am not able to do it, unable to dynamic the year in the endpoint. Please check the urls.py 2nd problem - i want to make requestedYear as dynamiic in views.py. Reference files are mentioned below. Please check. models.py class DataModel(models.Model): city = models.CharField(max_length=100) date = models.DateField(editable=True) serializers.py class DataSerializer(serializers.ModelSerializer): YearOfDate = serializers.SerializerMethodField() class Meta: model = DataModel fields = ['id', 'city', 'date', 'YearOfDate'] views.py class DataListView(generics.ListAPIView): serializer_class = DataSerializer model = DataModel queryset = model.objects.all() def get_queryset(self): requestedYear = 2009 return DataModel.objects.filter(date__year=requestedYear) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/data/2009', views.DataListView.as_view()), #re_path(r'^api/match/(?P<year>[0-9]{4})/$', views.DataListView.as_view()),] -
Two dependent conditions in exclude DJANGO
I want to check whether the current user already has the same movie id in his personal list or not. If he has it then I want to exclude that movie from my trending list. I want it to be something like this. views.py trending = list(Movies.objects.exclude(mid in mymovies WHERE uid = request.user.id)) -
Django "No Patterns" / Circular Import Error
I've scoured all of the issues I can find about this error and tried all of the solutions, yet none (save one; more on that later) worked for me. Every time I start up my app, I get the following error: django.core.exceptions.ImproperlyConfigured: The included URLconf 'gamerank.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. I've checked my files for circular imports, and cannot find any at all. voting/urls.py only imports voting/views.py voting/views.py imports voting/models.py, voting/helpers.py, and voting/forms.py voting/models.py imports from libraries only voting/helpers.py imports from libraries only voting/forms.py imports from voting/models.py (which does not import from voting/forms.py) This answer works for me, but I cannot access any of my application after that (because I just commented out the routes), so it's not really a solution in my case. Here are some of my files: voting/urls.py from django.urls import path from . import views app_name = 'voting' urlpatterns = [ path('', views.index, name="index"), # auth routes path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register") ] gamerank/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', … -
Is it possible to map all static files or url routes of a website?
I want to make a few static files available in my server, but I don't want people to access it unless they know the exact URL. This is meant to work like a game, solve a puzzle and move to the next phase by finding out the URL. Surely there are several similar games in the web. What I'm worried is if someone could just avoid the puzzle by "mapping" all the static files in a server. Is that possible? [Assuming the puzzle solution would lead to a static file served] I would like to extend the same question for URL routes, is it possible to discover all the url routes of a website? For example I have mysite.com and mysite.com/hidden/solution.html if there are no links to the second URL, can someone get this information? [Except bruteforcing] I'm hosting this page using AWS lightsail (django and apache). Is there something I can/need to do in the django/apache side to prevent this? -
Pycharm Django CSS not updating after adding git repo
I am creating a website and I was designing it without a repository set up originally. Now, I have it in a git repo and suddenly, when I try to refresh the page (with dev tools open and cache disabled) my CSS and HTML changes have no affect. I have to stop the server, close the webpage, then re-run the server and open it again to see changes. Anyone experienced this? Not sure what gives. -
inserting to SqlLite takes too long by django
hello i have 26 file (each ~100MB) i try to inserting by this view : def index(request): url = '../xaa' count = 0 line_num = 1660792 start = time.time() for lines in fileinput.input([url]): user = ast.literal_eval(lines) T.objects.create(a=user['a'], b=user['b'], c=user['c']) count += 1 percent = (100 * count) / line_num print(f"{percent}%") end = time.time() print(f"Time : {end - start}%") response = HttpResponse('Done') return response but it's take too long (3.5 day for a file) how can i do it faster ? -
Django Forms: field_order fails to work in forms.py
My field_order variable fails to correctly set the order. I'm trying to reorganize the form so that the bottom two fields are at the top of the form, as illustrated here: Here is my class from forms.py. I set the field_order in class Meta, but it doesn't re-arrange my form and I don't know why? I do not get any errors when I run my code either. class changeLockForm(forms.Form): def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(changeLockForm, self).__init__(*args, **kwargs) self.fields['roomLoc'] = forms.ModelChoiceField(queryset=Models.Room.objects.filter(owner=None) | Models.Room.objects.filter(owner=user), label='Room Location') self.fields['lockName'] = forms.ModelChoiceField(queryset=Models.Lock.objects.filter(owner=None) | Models.Lock.objects.filter(owner=user), label="Current Lock Name") newNameBool = forms.BooleanField(required=False, label='Change Name? Y/N',) newLockName = forms.CharField(required=False, min_length=2, max_length=20, label='New Lock Name', disabled=True) state = forms.BooleanField(required=False, label='LOCKED/UNLOCKED') code1 = forms.IntegerField(initial=1000, min_value=1000, max_value=9999, label='First Code') code2 = forms.IntegerField(initial=1000, min_value=1000, max_value=9999, label='Second Code') code3 = forms.IntegerField(initial=1000, min_value=1000, max_value=9999, label='Third Code') code4 = forms.IntegerField(initial=1000, min_value=1000, max_value=9999, label='Fourth Code') class Meta: model = Models.Lock fields = ['lockName','newNameBool','newLockName','roomLoc', 'state', 'code1', 'code2', 'code3', 'code4'] field_order = ['lockName', 'newNameBool', 'newLockName', 'roomLoc', 'state', 'code1', 'code2', 'code3', 'code4'] -
Heroku How to use django 1.11
this question have been asked, but my question is different. File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/admin/widgets.py", line 151 '%s=%s' % (k, v) for k, v in params.items(), I can solve this problem in my computer , but i don't know how to solve it on heroku django version:1.11 python:3.8.9 -
Django: Using the django-admin-sortable2 to manually order ManyToManyFields
models.py class Photo(models.Model): ... class Meta: ordering = ['id'] class Album(models.Model): title = models.CharField(max_length=100) photos = models.ManyToManyField(Photo,related_name="photos",blank=True) published = models.BooleanField(default=False) class Meta: ordering = ['title'] class AlbumToPhoto(models.Model): album = models.ForeignKey(Album,related_name="album_order",blank=True,on_delete=models.PROTECT) photo = models.ForeignKey(Photo,related_name="photos_order",blank=True,on_delete=models.PROTECT) photo_order = models.PositiveIntegerField(default=0) class Meta: ordering = ('photo_order',) admin.py from django.contrib import admin from adminsortable2.admin import SortableInlineAdminMixin from .models import Photo, Album class PhotoInline(SortableInlineAdminMixin, admin.TabularInline): # We don't use the Button model but rather the juction model specified on Panel. model = Album.photos.through # Register your models here. class PhotoAdmin(admin.ModelAdmin): list_display = ("title","index") class AlbumAdmin(admin.ModelAdmin): list_display = ("title","published") filter_horizontal = ("photos",) inlines = (PhotoInline,) admin.site.register(Photo, PhotoAdmin) admin.site.register(Album, AlbumAdmin) I have downloaded the package, django-admin-sortable2, and I followed this in their docs. However, I have this error: Model photos.models.Album_photos requires a list or tuple 'ordering' in its Meta class I am confused because both have Meta classes. Is it an error on my part or on theirs? Should I switch packages? -
RetrieveAPIView responding 404 - django rest
My RetrieveUpdateDestroyView keeps responding me with a list of objects from it's model serializer. And when I try to change the url, it keeps giving me a 404 error. I've already tried everything, don't know what is happening. This is my view.py class PersonListCreateAPIView(generics.ListCreateAPIView): serializer_class = PersonSerializer lookup_field = 'uuid' def perform_create(self, serializer): serializer.save(contact_of=self.request.user.get_team) def get_queryset(self): ''' This view should return a list of all the Person objects for the currently authenticated user team. ''' user = self.request.user return Person.objects.filter(contact_of=user.get_team) class PersonRetrieveUpdateDestroyAPIView(generics.RetrieveAPIView): serializer_class = PersonSerializer lookup_field = 'uuid' def get_queryset(self): user = self.request.user return Person.objects.filter(contact_of=user.get_team) This is my urls.py app_name = 'people' urlpatterns = [ # api/people/<uuid> path( route='<uuid:uuid>/', view=PersonRetrieveUpdateDestroyAPIView.as_view(), name='retrieve_update_destroy', ), # api/people/ path( route='', view=PersonListCreateAPIView.as_view(), name='list_create', ), ] Any help? -
Reading whitespace in heading of csv file using pandas
I need to read the heading from csv that have white between them, I need help to fix it. I try differnet way like delimiter = ' ' and delim_whitespace = True. Here is how I'm write the code: df = pd.read_csv( d, dtype = 'str', usecols=[ 'Owner First Name', 'Owner Last Name', 'StreetNumber', 'StreetName', 'State', 'Zip Code', 'Bdrms', 'Legal Description', 'Sq Ftg', 'Address', 'Orig Ln Amt', 'Prop Value' ], names=[ 'Owner_FirstName', 'Owner_LastName', 'StreetNumber', 'StreetName', 'State', 'ZipCode', 'Bdrms', 'Legal_Description', 'Sq_Ftg', 'Address', 'Orig_Ln_Amt', 'Prop_Value' ], skipinitialspace=True ) -
Passing an additional field through a model form without adding it to the model
I'm trying to figure out how to add a field to a model form without adding the field to the model itself. I just need to pass in this extra field to the view it returns. My django project has a page where the user uploads a text file which gets saved to the DB (the file upload form is the model form). It then returns a page where the important content from the text file is displayed. I want to add a dropdown on the same page as the file upload form that allows the user to select an option for how the content should be displayed when it returns the next page. I don't want this dropdown to be part of the model for the text file as I don't need to save it to the db. I'm having trouble figuring out how to pass this option into the view without adding it to the model itself. Upload form: <form method="POST" enctype="multipart/form-data" id="text-upload-form"> {% csrf_token %} {{ form.as_p }} <label for="display-type">Display type</label> <select id="display-type" name="display-type" form="text-upload-form"> <option value="highlighted">Highlighted display</option> <option value="dark">Dark display</option> </select> <button type="submit" class="save btn btn-default">Save</button> Views.py def parser(request): if request.method =='POST': text_upload = TextFileForm(request.POST, request.FILES) … -
Django user delete privilege role
Is possible to give roles/group to admin users to delete only the users they created? For example: admin1 created user1, user2 admin2 created user3, user4 admin1 should only have permissions to delete user1 and user2 and not have any access to user3 and user4. -
Django and jQuery: jQuery not working, but receiving no errors
I cannot figure out why my jQuery script isn't working. I've read through a bunch of stackOverflows but haven't been able to fix this issue. I have a form, and when a checkbox is checked, I want to enable a form field with the id div_id_newLockName. If the checkbox is unchecked, I want the form field to be disabled and greyed out. The checkbox has id div_id_newNameBool I have written code that I think should work, but it doesn't. I'm not receiving any errors though, which makes troubleshooting difficult. I'm hoping a second set of eyes can help. A picture of what the form looks like can be found here: In this picture, the "change name?" checkbox corresponds with div_id_newNameBool, and the "Lock Name" char field is what I want to toggle enable or disable. base.html (contains jQuery script) <!doctype html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <style> <!-- unimportant css stuff --> </style> <body class="w3-content" style="max-width:1200px"> <!-- !PAGE CONTENT! --> {% block content %}{% endblock %} <!-- End page content --> </div> <script> $(document).ready(function(){ if ($("#div_id_newNameBool").is(':checked')){ $("#div_id_newLockName").prop("disabled", false); } else { $("#div_id_newLockName").prop("disabled", true); alert("DISABLED"); } }); </script> </body> </html> HTML page for form {% extends "homepg/base.html" %} {% load crispy_forms_tags … -
How to get reference to object in django-restframework APIView
I am trying to fill a chart.js chart with historical values from my database of a Team object. Currently I have a regular django view which loads the template of the team, and a specific django rest-framework APIView that returns json response for the chart's labels and data, which sits inside of the template rendered by the initial django view. I need reference to the current team to be accessible in the APIView, but not sure how to do that. urls.py: path('team/<slug:slug>/', views.team_view, name='team_view'), path('teamChart', views.TeamChartData.as_view()), views.py: def team_view(request, slug): user = request.user team = Team.objects.get(slug=slug) ... return render(request=request, template_name='team_view.html', context={'team':team, 'form':form, 'userTeam': userTeam}) class TeamChartData(APIView): # authenticate user authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def get(self,request, format=None, *args, **kwargs): labels = ['hi'] chartLabel = "" chartdata = [1] data ={ "labels":labels, "chartLabel":chartLabel, "chartdata":chartdata, 'user':request.user.username, } return Response(data) teamChart.js var endpoint = '/teamChart'; $.ajax({ method: "GET", url: endpoint, success: function(data) { drawLineGraph(data, 'teamChart'); console.log("drawing"); }, error: function(error_data) { console.log(error_data); } }) function drawLineGraph(data, id) { .... } I've got the chart working for a user's account, but in the APIView I can reference the user from the request being made. I can't access the specific team page from that … -
Adding textarea in formset - django
I have a message form and a formset that includes questions for this message. I would like to add textareas in the form, instead of input field. - I am not sure why there are not many examples out there. The models looks like this: class Message(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) message_title = models.CharField(blank=True, null=True, max_length=255) message_introduction = models.TextField() def __str__(self): return self.message_title class Meta: db_table = 'messages' and: class Message_question(models.Model): message = models.ForeignKey(Message, related_name="message_questions", on_delete=models.CASCADE) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) message_question = models.TextField() def __str__(self): return self.message_question class Meta: db_table = 'message_questions' And the forms look like this: class MessageForm(forms.ModelForm): class Meta: model = Message fields = [ 'message_title', 'message_introduction', ] labels = { 'message_title': 'message_title', 'message_introduction': 'message_introduction', } widgets = {'created_at': forms.HiddenInput(),'updated_at': forms.HiddenInput()} class Message_questionForm(forms.ModelForm): class Meta: model = Message_question fields = ['message_question', ] widgets = { 'message_question': forms.TextInput(attrs={'class': 'formset-field', 'rows': 4}), } Is it doable and if yes, what element of the above code shoudl I change please ? -
Choose the correct option. ValidationError Django python
how to change validation from pk to name field in input forms? models class Service(models.Model): name = models.CharField(max_length=150, db_index=True, unique=True) def __str__(self): return self.name forms class SettingDeviceAddForm(forms.ModelForm): class Meta: model = Device fields = ['name'] that is, in the form, you need to enter a name and check the name field, and I enter the name, and the check goes along the pk field. how to change the default pk field to name html form -
I have a TypeError (Object … is not JSON serializable) when I try to set a session value (Django). Why?
I have this strange TypeError raised : "Object of type Product is not JSON serializable" when I try to set a session value in a view (in basket app). The error occurs with request.session['Hello'] = 'foo'. However, this error does not occur elsewhere. For instance, in store app, in views.py, the following request.session['Hello World'] = 'Alloy' works very well. Do you know why ? Basket app / views.py (it bugs) from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse from . basket import Basket from store.models import Product from discount.forms import UserDiscountForm def basket_summary(request): basket = Basket(request) context = {'basket':basket} request.session['Hello'] = 'foo' return render(request,"store/basket_summary.html",context) store app / views.py (it works well) from django.shortcuts import get_object_or_404, render from requests.sessions import session from .models import Category, Product def home(request): print('----------// HOME PAGE //----------') request.session['Hello World'] = 'Alloy' context = {} return render(request, 'store/home.html', context) Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/basket/ Django Version: 3.2 Python Version: 3.9.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store', 'account', 'basket', 'orders', 'payment', 'contact', 'address', 'discount', 'shipping'] 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'] Traceback (most recent call last): File "C:\Users\Utilisateur\Documents\Environments\monoi_django_virtualenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Utilisateur\Documents\Environments\monoi_django_virtualenv\lib\site-packages\django\utils\deprecation.py", line …