Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django moving javascript code and form outside a for loop
using django, I want to create a popup modal form when someone clicks on delete. I’m trying this thing I got from here : https://www.w3schools.com/howto/howto_css_modals.asp The problem is that I don’t want to repeat that form and js code on each for loop item, I want it outside the loop with a unique product pk or id on each click here my is html code: {% extends 'base.html' %} {% block content %} <div class="container"> {% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class=" {{ message.tags }} " {% endif %}> {{ message }} </li> {% endfor %} </ul> {% endif %} <div class="grid-container"> {% for product in products %} <div class="grid-item"> <div> <img src="{{ product.image_url.url }}" alt="{{ product.title }}"> <h5>{{ product.title }}</h5> <!-- DELETE Trigger/Open The Modal --> <button id="myBtn">Open Modal</button> </div> </div> <div id="myModal" class="modal"> <!-- Modal content --> <div class="modal-content"> <span class="close">&times;</span> <h1>are you sure you want to delete: "{{product.title}}"؟</h1> <form class="form_container" enctype="multipart/form-data" action="{% url 'delete' product.pk %}" method="post"> {% csrf_token %} <label for="pincode">enter your code to delte:</label> <input type="number" id="pincode" name="pincode"> <input type="submit" name="Confirm" value="delete"> </form> </div> </div> <script> var modal = document.getElementById("myModal"); // Get the button … -
Django actions on admin re-query SQL so time waiting is double
I have model using the DjangoQLSearchMixin for filtering class FollowerAdmin(DjangoQLSearchMixin, NumericFilterModelAdmin, SpecialActions): and I use also def get_queryset(self, request): I get the results on the admin page, later I export to csv using : But it do the sql query over again after I export. Any idea Y ? -
StreamingHttpResponse not working with ASGI but work fine with WSGI
I'm trying to use channels for some WebSockets-related stuff, but it keeps loading and not showing any streaming response when I reload my web page. Here is my code which works fine with this setting: # settings.py # WSGI_APPLICATION = 'main.wsgi.application' # work fine ASGI_APPLICATION = "main.asgi.application" # not working And here is my views.py: @gzip.gzip_page # for performance def video_stream(request: HttpRequest): video = VideoContainer.objects.last() video_path = video.file.path return StreamingHttpResponse(generate_frames(VideoCamera(video_path)), content_type="multipart/x-mixed-replace;boundary=frame") Here is my code for generate_frames and VideoCamera: import cv2 class VideoCamera: def __init__(self, video_path: str): self.video = cv2.VideoCapture(video_path) def __del__(self): self.video.release() def get_frame(self): while (self.video.isOpened()): img = self.video.read()[1] # because web-page looking for image/jpeg content type jpeg = cv2.imencode(".jpg", img)[1] return jpeg.tobytes() # we stream it in byte form for frontend def generate_frames(camera) -> bytes: while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') -
When creating a package, how do I manage migrations of a weak dependency?
I have a Django app that I would like to package and offer the community through Pipy. Its only strong dependance is Django. It also integrates nicely with Django CMS and offers additional integration for Django CMS. I plan to offer this additional functionality only to projects with Django CMS installed. (This is what I call a weak dependency - will install and work without it, but work even bitter with it.) Specifically, some models are only defined if the base model CMSPlugin from Django CMS is installed. Is there a good/right way to manage migrations, though? I cannot include migrations of models depending on CMSPlugin in the package since users w/o a Django CMS installations will not be able to run it. If I omit the migrations depending on CMSPlugin users with Django CMS will create them on first installation. I fear, however, that on every update of the package those migrations will be lost on pip install upgrade when the package is overwritten. -
Incorrect string value: '\\xF0\\x9F\\x88\\xB2\\xE4\\xB8...' for column 'welcome_msg' at row 1
I got this problem when saved the object by Django. I have checked my table CharSet, As the following picture. I dont know why this happen, Thanks for any ideas! -
django rest framework how to check if phone already exist?
I want to check if phone number is already existing or not. My serializer class teacherInfoCustomSer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ['first_name', 'last_name', 'phone'] apiView def teacherInfoCustom(request, pk): custom = CustomUser.object.get(id=pk) serializer = teacherInfoCustomSer(instance = custom, data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) and my JS let data1 = JSON.stringify({ "first_name": tch_name.value, "last_name": tch_lastname.value, "phone": tch_phone.value }) const teacherInfoCustom = ('/p/teacherInfoCustom/' + "{{ request.user.id }}") fetch(teacherInfoCustom, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken }, body: data1, }).then((response) => { console.log(response) }).catch(err => { console.log(err.response.message) }) In model's phone field phone = models.CharField(max_length=15, unique=True, blank=True, null=True) and if a phone number already exist it won't give me status 400 but gives status 200 and it didn't save(i think because I set unique=True in my model). And if I enter phone number that didn't exist it will save. -
ValueError: The view did not return an HttpResponse object
I am writing a Django server. I had to use generic views for my API class. Now, Whenever I test the code using postman, everything works fine. But if I test it using other clients like Talend API tester or my Chrome browser, it returns 500 Error saying API did not return any HttpResponse object. Here's my skeleton codebase @method_decorator(csrf_exempt, name='dispatch') class ClassName(View): @throttle def post(self, request) -> JsonResponse: try: data = (json.loads(request.body)) except JSONDecodeError: # decoding error of Json File. msg = "An error occurred while decoding the input" return message_handler(msg, 500) ...... some other application logic ...... return JsonResponse({ "status": True, "message": "", }, status=200) All of my API is using the same format, they are returning a JsonResponse, so what am I doing wrong? -
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 )