Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: 'MediaDefiningClass' object is not iterable when using nested_admin
I have used the nested_admin to use Inlines to get a customized view at Admin Dashboard. Here is my admin.py from django.contrib import admin from .models import Quizzes, Question, Answer, UsersAnswer, QuizTakers import nested_admin class AnswerInline(nested_admin.NestedTabularInline): model = Answer extra = 4 max_num = 4 class QuestionInline(nested_admin.NestedTabularInline): model = Question inlines = [AnswerInline,] extra = 19 class QuizAdmin(nested_admin.NestedModelAdmin): inlines = [QuestionInline,] class UsersAnswerInline(admin.TabularInline): model = UsersAnswer class QuizTakersAdmin(admin.ModelAdmin): inlines = [UsersAnswerInline,] admin.site.register(UsersAnswerInline) admin.site.register(QuizTakers, QuizTakersAdmin) admin.site.register(Quizzes, QuizAdmin) And also included the path in the main urls.py: path('nested_admin/', include('nested_admin.urls')), But I am getting this error : for model in model_or_iterable: TypeError: 'MediaDefiningClass' object is not iterable -
No data insertion in the database in django when form is been submited
I am trying to create a registration form using Django as I have created the form and model on the website after clicking the submit it calls for the view as action provided to the form but it seems that no data is been inserted in the database and no error in the terminal as well. I have tried to find solutions but none of them worked. I am new in the field of python and web development. below is the code that I have used on the website. model.py from django.db import models class Writer(models.Model): username = models.CharField(max_length=30) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(max_length=254) contactnumber = models.IntegerField() gender = models.CharField(max_length=30) password = models.CharField(max_length=254) date = models.DateField() class Meta: db_table = 'Writers' below code are of my views.py views.py def createuser(request): if request.method == 'POST': username = request.POST.get('username') first_name = request.POST.get('firstname') last_name = request.POST.get('lastname') email = request.POST.get('email') contactnumber = request.POST.get('phonenumber') gender = request.POST.get('gender') password = contactnumber if username == None or first_name == None or last_name == None or email == None or contactnumber == None or gender == None: return render(request,"adminpanal/userregister.html",{'alert_flag': True}) else: createnewuser = Writer(username=username,first_name=first_name,last_name=last_name,email=email,gender=gender,contactnumber=contactnumber,password=password,date=datetime.today()) createnewuser.save() return redirect('/Blogdashboard/dashboard') return HttpResponse("Doen,user created") below are the Html … -
Get all elements that contain a specific tag in django-rest-framework
I am using django-rest-framework and django-taggit to add tags to my models. My models are movie and book and both have only a title and tags from django.db import models from taggit.managers import TaggableManager class Movie(models.Model): title = models.CharField(max_length=255, unique=True) tags = TaggableManager() def __str__(self): return self.title class Book(models.Model): title = models.CharField(max_length=255, unique=True) tags = TaggableManager() def __str__(self): return self.title I serialize the models and build the views serializers.py from rest_framework import serializers from taggit_serializer.serializers import (TagListSerializerField, TaggitSerializer) from .models import Movie, Book class MovieSerializer(TaggitSerializer, serializers.ModelSerializer): tags = TagListSerializerField() class Meta: model = Movie fields = ( 'id', 'title', 'tags', ) class BookSerializer(TaggitSerializer, serializers.ModelSerializer): tags = TagListSerializerField() class Meta: model = Book fields = ( 'id', 'title', 'tags', ) views.py from rest_framework import viewsets from .models import Movie, Book from .serializers import MovieSerializer, BookSerializer class MovieViewSet(viewsets.ModelViewSet): serializer_class = MovieSerializer queryset = Movie.objects.all() class BookViewSet(viewsets.ModelViewSet): serializer_class = BookSerializer queryset = Book.objects.all() Here are also my ulrs.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('apps.movie.urls')), path('api/', include('apps.book.urls')), ] from django.urls import path, include from rest_framework import urlpatterns from rest_framework.routers import DefaultRouter from .views import MovieViewSet, BookViewSet router = DefaultRouter() router.register('movie', MovieViewSet, basename='movie') router.register('book', BookViewSet, … -
About using jinja templating in JS file
I have been using a template in which there's images of previous and next button is in JavaScript file. The Framework I'm using is Django, is there any solution to use jinja templating/rendering for these images in JS file. JS code: $(".active-banner-slider").owlCarousel({ items:1, autoplay:false, autoplayTimeout: 5000, loop:true, nav:true, navText:["<img src={% static 'img/banner/prev.png' >","<img src={% static 'img/banner/next.png' %}>"], dots:false }); I used same static method with html files and it worked, I don't know if this method does even work with JS file or not? if it does what would be the correct way? -
blog detail template does not exist error
I have a simple blog app which has a blog list view and their detail pages that are generated automatically. everything seems to work just fine in local. however after I deployed the app on the server when I click to see the detail page I get a Template does not exist error. this is my views: class BlogMain(ListView): model = BlogPost template_name = 'Blog/Blog-news.html' queryset = BlogPost.objects.all() context_object_name = 'posts' ordering = ['-published'] paginate_by = 3 def get_context_data(self, **kwargs): context = super(BlogMain, self).get_context_data(**kwargs) context['tags'] = BlogPost.tags.all() return context class BlogTags(ListView): model = BlogPost template_name = 'Blog/Blog-news.html' context_object_name = 'posts' def get_queryset(self): return BlogPost.objects.filter(tags__slug=self.kwargs.get('tag_slug')) def get_context_data(self, **kwargs): context = super(BlogTags, self).get_context_data(**kwargs) context['tags'] = BlogPost.tags.all() return context class BlogDetail(DetailView): model = BlogPost template_name = 'Blog/Blog-news-detail.html' context_object_name = 'blog' slug_url_kwarg = 'the_slug' slug_field = 'slug' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["related_items"] = self.object.tags.similar_objects()[:3] return context this is my urls: path('blog/', views.BlogMain.as_view(), name="blog-page"), path('log/tags/<slug:tag_slug>/', views.MaghaleTags.as_view(), name="tagged"), re_path(r'blog/(?P<the_slug>[-\w]+)/', views.BlogDetail.as_view(), name='post-detail'), and finally my templates: {% for post in posts %} <div class="container-fluid blog-main mb-5"> <a href="{% url 'post-detail' post.slug %}"> <div class="row"> <div class="col-lg-5 pt-5 pb-3 my-5"> <h5>{{ post.title | persianize_digits }}</h5> <small> {% for tag in post.tags.all %} {{ tag.name }} {% … -
Getting a NoReverseMatch error Django when creating url link in template
not sure why I'm getting this error , I have checked my views and paths , which i think seem fine, the noreversematch error I get shows the arguments ('wonderful', 'bass', 1)' are correct, but it throws back this error: NoReverseMatch at /instrument-detail/wonderful/1/ Reverse for 'create_eq' with arguments '('wonderful', 'bass', 1)' not found. 1 pattern(s) tried: ['create\-eq/(?P<track_slug>[-a-zA-Z0-9_]+)/(?P<instrument_slug>[-a-zA-Z0-9_]+)/int:id>/$'] here are my views, urls, models, and the template where i have the link to 'create_eq' : urls.py path('create-eq/<slug:track_slug>/<slug:instrument_slug>/int:id>/', views.create_eq, name='create_eq'), path('instrument-detail/<slug:track_slug>/<int:id>/', views.instrument_detail, name='instrument_detail'), views.py @login_required def create_eq(request, track_slug, instrument_slug, id): user = request.user track = get_object_or_404(Track, id=id) instrument = get_object_or_404(Instrument, id=id) if request.method == "POST": form = EQCreateForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.user = user data.save() return redirect('profile', slug=track.slug, id=track.id) else: form = EQCreateForm() return render(request, 'feed/create_eq.html', {'form': form }) @login_required def instrument_detail(request, track_slug, id): user = request.user track = get_object_or_404(Track, id=id) my_inst = Instrument.objects.filter(track_id=track.id) instrument_obj = get_object_or_404(Instrument, id=id) if my_inst.exists(): instruments = Instrument.objects.filter(track_id=track.id) context = { 'instruments': instruments, 'track': track, 'instrument': instrument_obj, } return render(request, 'feed/instrument_detail.html', context) else: print('There are no instruments set in your track') return redirect('create_instrument', track_slug=track.slug, id=track.id) models.py class Instrument(models.Model): title = models.CharField(max_length=120) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) track = models.ForeignKey('Track', on_delete=models.CASCADE, null=True) artist = models.ForeignKey(User, … -
Django / pytest: Command line paramter visibility in setUpClass()?
I want to call pytest with an additional command line parameter. I want to use this parameter in the setUpClass() method. What I tried so far is this, but I cannot figure out how to do the check for --foo in setUpClass(). conftest.py from pytest import fixture def pytest_addoption(parser): parser.addoption("--foo", action="store_true") @fixture(scope='class') def headless(request): return request.config.getoption("--foo") test_something.py from django.test import LiveServerTestCase class SomeTest(LiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() # ?? how do I check here whether '--foo' was given as command line parameter ?? -
Django : how to change button color based on value _list
I want to change a button color based on values from my database. I'm using this code : {% if result %} {% for of in result %} <a data-container="body" data-toggle="popover" data-placement="right" data-content='NO OF: {{of.0}} _ Jour ATT: {{of.2.days}} _ Date Entrée: {{of.1}} '> <span class="{% if '{{of.2}}' > 2 %} dot red {% endif %} {% elif '{{of.2}}' == 2 %}dot red {% endif %} {% else %}dot{% endif %}"></span> </a> {% endfor %} {% else %} <p>Encours Vide</p> {% endif %} i used aslo: <a data-container="body" data-toggle="popover" data-placement="right" data-content='NO OF: {{of.0}} _ Jour ATT: {{of.2.days}} _ Date Entrée: {{of.1}} '> {% if '{{of.2}} >=3' %}<span class="dot red"></span> {% elif '{{of.2}} ==2' %}<span class="dot yellow"></span> {% else %}<span class="dot"></span> {% endif %} </a> both doesn't work, how can I check values list in my html code correctly? Views.py: result=Poste.objects.filter(Nom_poste='MGP1').values_list('OF__Numero_Of','OF__Date','OF__Nbre_jr') css code of dot: .dot {height: 30px; width: 30px;background-color: #0f5132;border-radius:50%;display:inline-block;} .red{background-color:#d00000;} .yellow{background-color: #ffc107;} I don't know how to do this in JS, so tried to simplify my code. Any suggestions? -
Django Filter Data with Country for user assigned to
Account App Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.DO_NOTHING) countries = models.ManyToManyField(CountryMaster) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Data App views.py def CreateData(request): form = CreateDataModelForm(request.POST or None) profiles = Profile.objects.all() a = [] for profile in profiles: b = profile.sites.all() a.append(b) **data = DataMaster.objects.filter( CountryName__in=a).order_by('-id')[:7]** if form.is_valid(): note = form.save(commit=False) note.createdby = request.user note.save() Problem: I am not able to filter data with the Profiles mapped to a country -
Cannot install Postgis on Heroku CI
I am getting the following error when deploying my app for a test in Heroku: self = <django.db.backends.utils.CursorWrapper object at 0x7f634cc50a00> sql = 'CREATE EXTENSION IF NOT EXISTS postgis', params = None ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0x7f635095d2b0>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0x7f634cc50a00>}) def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: # params default might be backend specific. > return self.cursor.execute(sql) E django.db.utils.OperationalError: could not open extension control file "/app/.indyno/vendor/postgresql/share/extension/postgis.control": No such file or directory .heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py:82: OperationalError I have the following code in my app.json file: { "buildpacks": [ { "url": "https://github.com/heroku/heroku-geo-buildpack.git" }, { "url": "heroku/python" } ], "environments": { "test": { "addons": [ "heroku-postgresql:in-dyno" ], "scripts": { "test": "pytest" } } } } From what I concluded, I see that the error happens when the SQL command 'CREATE EXTENSION IF NOT EXISTS postgis' is executed. -
DjangoAdmin TypeError: '<' not supported between instances of 'str' and 'int'
In a normal python program, I understand what this problem means but I am not able to find the reason behind this error while saving posts from admin in Django. Have I given any invalid data according to field? So while saving it gives the following error: Environment: Request Method: POST Request URL: http://localhost:8000/admin/blog/post/add/ Django Version: 3.2.4 Python Version: 3.6.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog'] 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 "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 232, in inner return view(request, *args, **kwargs) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1657, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1540, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1579, in _changeform_view form_validated = form.is_valid() File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/forms/forms.py", line 175, in … -
Why django-mptt shows error: unsupported operand type(s) for -: 'str' and 'str'?
models.py -> class Category(MPTTModel): title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) parent = TreeForeignKey( 'self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class MPTTMeta: order_insertion_by = ['title'] class Card(models.Model): categories = TreeManyToManyField(Category, related_name='category_cards', blank=True, default=None) admin.py -> @admin.register(Category) class CategoryAdmin2(DraggableMPTTAdmin): list_display = ('tree_actions', 'indented_title',) list_display_links = ('indented_title',) In admin interface, I get this error: TypeError at /admin/myapp/category/3/change/ unsupported operand type(s) for -: 'str' and 'str' How to solve it? -
PYTHON REQUEST.SESSION VARIABLES ARE DISAPPEARING ON ITS OWN
I am setting a session variables everytime I logged in. The thing is, if I use the local ip '127.0.0.1:8000' to run my python-django web, the session variables is working properly. But if I use my original IP '192.168.2*.***' after I set the value of every session variables, after seconds the variables itself cannot be called, I mean I got an error the session variables isn't declared 'KeyError: username' This is my codes in logging in, I use ajax and replace the document.location.href to Home url if the ajax data returns 'valid' @csrf_exempt def CheckLogin(request): if request.method == 'POST': id = request.POST['id'] query = query_api( "SELECT * FROM user_tbl WHERE employee_id='" + id + "';") if len(query) == 0: return JsonResponse({"data": "Invalid username"}, safe=False) request.session['test'] = "asdjkahsdkjhk" request.session['logged_in'] = True request.session['username'] = id request.session['password'] = "1234" request.session['role'] = query[0]["role"] test = json.dumps(query, indent=4, cls=DateTimeEncoder) return JsonResponse({"data": "valid", "password": test, "role": query[0]["role"]}, safe=False) return JsonResponse({"data": "invalid ajax"}, safe=False) While these are my codes in checking whether it is for log in or already logged-in. @csrf_exempt def CheckifLoggedin(request): if 'logged_in' in request.session: return JsonResponse({"data": "logged_in"}, safe=False) return JsonResponse({"data": "for log-in"}, safe=False) If I try to get the username using this code: username … -
Django Error AttributeError: module 'something' has no attribute 'function'
I am Getting error in changing the Default page of my Django app I am doing it with help of function based view, by importing a function from a view of an app of my project My code in urls.py of project is: from page import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.op1,name='home'), ] Please help me in finding the mistake..... -
How to await a channel_layer.group_send (with @database_sync_to_async) inside a Celery shared_task?
I have a AsyncWebsocketConsumer where one method uses @database_sync_to_async to save the connected user data to the database. Now I want to call this from outside (in a celery shared_task) via channel_layer.group_send. But how can I wait for all the connected users db-operations to go through before continuing the task? Later in the shared_task I want to get all the updated db-records and brodcast it to the same group. I thought a async_to_sync wrapping the channel_layer.group_send would do this. But it sends immediately before all db-operations is done. (A work around is by putting a time.sleep(8) in between but I don't like this approach because I really dont know how long exactly it would take.) -
Django Queries Count and update
I have the following two models ASPBoookings and Athlete. The Athlete model is linked to the ASPBookings model by the foreign key named athlete. I was recently shown queries/subqueries with Views and I have been trying to use them (still learning) to provide a count of all bookings assigned to each athlete within the ASPBookings table. Once I then have the information I need the "number_of_asp_sessions" within the Athlete model to be automatically updated with each of the athletes bookings count. e.g. Athlete ID 1, may have two bookings assigned. Athlete ID 2, may have one booking assigned. The number_of_asp_sessions should then show these numbers for each of the athletes. Hope this makes sense and thanks for advance for any help. Appreciate it. Below is the code: ASPBookings Model class ASPBookings(models.Model): asp_booking_ref = models.CharField(max_length=10, default=1) program_type = models.CharField(max_length=120, default='asp') booking_date = models.DateField() booking_time = models.CharField(max_length=10, choices=booking_times) duration = models.CharField(max_length=10, choices=durations, default='0.5') street = models.CharField(max_length=120) suburb = models.CharField(max_length=120) region = models.CharField(max_length=120, choices=regions, default='Metro') post_code = models.CharField(max_length=40) organisation_type = models.CharField(max_length=120,choices=organisation_types, default='Government School') audience_number = models.CharField(max_length=10) presentation_form = models.CharField(max_length=120, choices=presentation_form_options, default='Face to Face') contact_name = models.CharField(max_length=80) email = models.EmailField() phone_number = models.CharField(max_length=120) comments = models.TextField() status = models.CharField(max_length=80, choices=statuses, default='TBC') email_sent = models.BooleanField(default=False) … -
problem with applying migrations in the project
I want to make a move in my project, I write python3 manage.py makemigrations and I get this error Traceback (most recent call last): File "/Users/work/Projects/ims/api/manage.py", line 21, in <module> main() File "/Users/work/Projects/ims/api/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/config.py", line 224, in create import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'corsheaders' for more details on how I arrived at this error, you can go to my previous question [https://stackoverflow.com/questions/68228238/cant-make-migrations/68228429?noredirect=1#comment120585207_68228429] init.py """A pure Python implementation of import.""" __all__ = ['__import__', 'import_module', 'invalidate_caches', 'reload'] # Bootstrap help ##################################################### # Until bootstrapping is complete, DO NOT import any modules that attempt # to import importlib._bootstrap (directly or indirectly). Since this # partially initialised package would be present in sys.modules, those # modules would get an uninitialised copy of the source version, instead # of a fully initialised version (either the frozen one or … -
Django REST API POST to Python script
Is it possible to run a Python script with the POST data as soon as a POST request is triggered or a new entry added to the Django REST API ? I'm very new to Django, please explain in detail for answer. -
Django receiving duplicate signals when updating content from HTML page
I am getting duplicate of each content when updating content from html page. see the picture: I am not getting any duplicate when updating from Django admin panel. How to avoid duplicate when updating from HTML template? here is my code I think I am doing any mistake in my views. here is my views.py class ApproveCommentPage(UpdateView): model = BlogComment template_name = "blog/approve_comment.html" form_class =AdminComment def form_valid(self, form): self.object = form.save() status = self.object.is_published name = self.object.name[0:20] messages.success(self.request, f"{name} comment status {status}") return super().form_valid(form) -
django.db.utils.ProgrammingError: relation "testingland_mapcafes" does not exist
So I am having major Postgres/Django dramas. I kept getting the following error: django.db.utils.ProgrammingError: relation "testingland_mapcafes" does not exist I tried deleting migrations cache, checking and rechecking make migrations, running python3 manage.py migrate testingland zero and then running migrate I have no idea what is going wrong when I check tables in PSQL (db is called vygr) i see the following: Schema | Name | Type | Owner --------+----------------------------+-------+-------------- public | auth_group | table | x public | auth_group_permissions | table | x public | auth_permission | table | x public | auth_user | table | x public | auth_user_groups | table | x public | auth_user_user_permissions | table | x public | django_admin_log | table | x public | django_content_type | table | x public | django_migrations | table | x public | django_session | table | x public | spatial_ref_sys | table | x My settings.py are set up like this: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'vygr', 'USER': 'xxx', 'PASSWORD': 'xxxx', 'HOST': 'localhost', 'PORT': '5432' } } Here is the model in question which does exist but not as a table in my db (yet?): class mapCafes(models.Model): id = models.BigAutoField(primary_key=True) cafe_name = models.CharField(max_length=200) cafe_address = … -
Field 'id' expected a number but got [<django.db.models.sql.query.Query object at 0x000002CFD4506EC8>]
I am building a BlogApp and I am trying to exclude posts with another another model field. BUT when i go to browser then this error is keep showing Field 'id' expected a number but got [<django.db.models.sql.query.Query object at 0x000002CFD4506EC8>]. models.py class Post(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') tags = TaggableManager() class AddFav(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='parent_user') favourite_users = models.ManyToManyField(User, related_name='favourite_users', blank=True) blocked_tags = TaggableManager() views.py def posts(request): block_or_not = AddFav.objects.filter(favourite_users=request.user) exclude_this_list = [] for excluding in block_or_not: exclude_this = excluding.blocked_tags.all() exclude_this_list.append(exclude_this) posts = Post.objects.filter(date_added__lte=now).exclude(tags=exclude_this_list) I have no idea what is wrong in this. Any help would be much Appreciated. Thank You in Advance. -
Django sort by annotate in model Meta
Is there a way to set ordering in a models Meta class by an annotated field? i.e. class ModelA(models.Model): name = models.CharField() class ModelB(models.Model): name = models.CharField() model_a = models.ForeignKey(ModelA) This is what i can do for queryset but need same way to do on class Meta if possible ModalA.objects.all() .annotate( count_b=Count("modal_a") ) .order_by("count_b") -
Creating Django Models
I have been working on Django. But it’s quite new to me can you guys please help me actually I am trying to create a backend work using Django which has 2 models but how do I create I am not able to understand and add it to the admin page. The image shows 2 models 1st model stores the basics over the layout of jobs and while clicking on them it is transferred to the 2nd model which stores detail of that info. Please help me with it code guys. enter image description here -
load csv into sqlite3 db (django)
I am trying to load the csv files I upload to my sqlite3 db. I am able to upload the csv into a folder but it doesn't appear on my db. The db table structure contains as many columns as the csv with the corresponding data types; but the column names in the db table structure are different as in the csv, as some of the columns names in the csv contain spaces and special characters (like accents for example). My goal is to allow the user to upload a csv file that will be loaded to the db. I was also wondering if its possible to increment the db each time a new csv is loaded (for example: I upload a file now which is loaded to the db then the second time I add, the newer details are added to the db without deleting the previous ones). Apologies if I am unclear and asking too many things at once. Here is my model, form, function (handle upload) & views .py files: models.py class UploadForm(models.Model): file = models.FileField() class Meta: db_table = "db_table" forms.py class UploadForm(forms.ModelForm): class Meta: model = UploadForm fields = "__all__" functions.py def handle_uploaded_file(f): with open('vps_app/static/upload/'+f.name, … -
How to access two fields in two separate HTML pages to carry out a JavaScript function in a Django project?
I have two models: class Package(models.Model): rt_number=ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=ForeignKey(Treatment, on_delete=CASCADE) patient_type=ForeignKey(PatientType, on_delete=CASCADE) date_of_admission=models.DateField(default=None) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) class Receivables(models.Model): rt_number=ForeignKey(Patient, on_delete=CASCADE) discount=models.DecimalField(max_digits=9, decimal_places=2, default=None) approved_package=models.DecimalField(max_digits=10, decimal_places=2, default=None) proposed_fractions=models.IntegerField() done_fractions=models.IntegerField() base_value=models.DecimalField(max_digits=10, decimal_places=2) expected_value=models.DecimalField(max_digits=10, decimal_places=2) forms.py: class PackageForm(ModelForm): class Meta: model=Package fields='__all__' widgets={ "patient_type" : forms.Select(attrs={"onblur":"mf();"}), "max_fractions" : forms.NumberInput(attrs={"onfocus":"mf();", "onblur":"tp();"}), "total_package" : forms.NumberInput(attrs={"onfocus":"tp();", "onblur":"onLoad();"}), } class ReceivablesForm(ModelForm): class Meta: model=Receivables fields='__all__' widgets={ "approved_package":forms.NumberInput(attrs={"onfocus":"onLoad();"} ) } views.py: def package_view(request): if request.method=='POST': fm_package=PackageForm(request.POST, prefix='package_form') if fm_package.is_valid(): fm_package.save() fm_package=PackageForm(prefix='package_form') return render (request, 'account/package.html', {'form5':fm_package}) else: fm_package=PackageForm(prefix='package_form') return render (request, 'account/package.html', {'form5':fm_package}) def receivables_view(request): if request.method=='POST': fm_receivables=ReceivablesForm(request.POST) if fm_receivables.is_valid(): fm_receivables.save() fm_receivables=ReceivablesForm() return render(request, 'account/receivables.html', {'form6':fm_receivables}) else: fm_receivables=ReceivablesForm() return render(request, 'account/receivables.html', {'form6':fm_receivables}) templates-package: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Package Form</title> </head> <body> <form action="" method="post" novalidate> {% csrf_token %} {{form5.as_p}} <button onclick="tots()" type="submit">Save</button> </form> <script src="{% static 'account/js/myjs.js' %}"></script> <script src="{% static 'account/js/test.js' %}"></script> </body> </html> Its source page view for total package field: <p><label for="id_package_form-total_package">Total package:</label> <input type="number" name="package_form-total_package" onfocus="tp();" onblur="onLoad();" step="0.01" required id="id_package_form-total_package"></p> <button onclick="tots()" type="submit">Save</button> templates-receivables: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Receivables</title> </head> <body> <form action="" method="post"> …