Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.ProgrammingError: relation x does not exist
Apologies if this question has already been asked, however I could not find a working solution among the answers. I have the 'training_log' app, also added in the project's settings.py. In training_log\models.py: class SessionType(models.Model): name = models.CharField(max_length=80) def __str__(self): return f"{self.name}" class Exercise(models.Model): name = models.CharField(max_length=100) session_type = models.ForeignKey(SessionType, on_delete=models.CASCADE) def __str__(self): return f"{self.name}" class TrainingLog(models.Model): session_type = models.ForeignKey(SessionType, on_delete=models.CASCADE, null=True) exercises = models.ManyToManyField(Exercise) comments = models.TextField(max_length=500) date_posted = models.DateField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): exercises = ', '.join(str(ex) for ex in self.exercises.all()) return f"{self.session_type}- {self.date_posted}- {exercises}" I am using postgresql. When I try to run the makemigrations command, I get this error: django.db.utils.ProgrammingError: relation "training_log_sessiontype" does not exist LINE 1: ...ype"."id", "training_log_sessiontype"."name" FROM "training_... Before using postgresql, I was using sqlite3, and the migrations worked only if I added the models one by one and ran migrations after each of them. I have tried deleting the db files and the migrations folders to no avail. Could anyone please shed some light on this issue? Thank you in advance. -
Why celery not executing parallelly in Django?
I am having a issue with the celery , I will explain with the code def samplefunction(request): print("This is a samplefunction") a=5,b=6 myceleryfunction.delay(a,b) return Response({msg:" process execution started"} @celery_app.task(name="sample celery", base=something) def myceleryfunction(a,b): c = a+b my_obj = MyModel() my_obj.value = c my_obj.save() In my case one person calling the celery it will work perfectly If many peoples passing the request it will process one by one So imagine that my celery function "myceleryfunction" take 3 Min to complete the background task . So if 10 request are coming at the same time, last one take 30 Min delay to complete the output How to solve this issue or any other alternative . Thank you -
Django Slugify not loading categories with two words
I add the category section in the model and the slugify function loads posts with one-word category but it's not loading the posts with multiple words View Function: def CategoryView(request, cats): category_posts = Item.objects.filter(item_category__slug=cats.replace('-', '')) return render(request, 'waqart/categories.html', {'cats':cats, 'category_posts':category_posts }) Model: class Categories(models.Model): name = models.CharField(max_length=200) summary = models.CharField(max_length=200) slug = models.CharField(max_length=200) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name -
Saving form data to models.ForeignKey fields
I am working on a web-app which store books details.I created a form page to add details of books in database. when i am submitting that form it gives me error. valueError: Cannot assign "'scifi'": "Book.genre" must be a "Genre" instance. Is there any way to assign data from submitted form to the models.ForeignKey(Genre,on_delete=models.CASCADE,null=True) which is in Book class. models.py class Genre(models.Model): title=models.CharField(max_length=100) class Meta: verbose_name_plural='2. Genre' def __str__(self): return self.title class Language(models.Model): title=models.CharField(max_length=100) class Meta: verbose_name_plural='3. Language' def __str__(self): return self.title class Book(models.Model): image=models.ImageField(upload_to="book_imgs/",null=True) title=models.CharField(max_length=200,null=True) Author=models.CharField(max_length=200,null=True) genre=models.ForeignKey(Genre,on_delete=models.CASCADE,null=True) language=models.ForeignKey(Language,on_delete=models.CASCADE,null=True) class Meta: verbose_name_plural='1. Book' def __str__(self): return self.title def image_tag(self): return mark_safe('<img src="%s" width="50" height="50" />' % (self.image.url)) views.py def add_books(request): if request.method =="POST": bookname= request.POST['bookname'] author= request.POST['author'] genre= request.POST['genre'] language= request.POST['language'] instance = Book(title=bookname,Author=author,genre=genre,language=language) instance.save() return render(request,'Add_books.html') -
Django always throwing weird errors with all its command
django-admin startproject is the only command that ran successfully i am on 3.9.6 tching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/usr/local/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/local/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 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 122, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 326, in add_to_class value.contribute_to_class(cls, name) File "/usr/local/lib/python3.9/site-packages/django/db/models/options.py", line 207, in contribute_to_class self.db_table = … -
Fetch subset columns from a Django API
I would like to get some columns of my Django API data. How can I do to get specific column without pulling all data as the does the following script ? var data_from_api; fetch('http://127.0.0.1:8000/api/network/1/edges/') .then((response) => { return response.json() }) .then((data) => edges_from_api=data) I just want to get lanes, length and speed. Subset of my api data [ { "id": 1, "edge_id": 1, "name": "Out 1 - E", "length": 4.0, "speed": 50.0, "lanes": 1, "param1": 3000.0, "param2": null, "param3": null, "road_type": 2, "source": 1, "target": 2 }, { "id": 2, "edge_id": 2, "name": "Out 1 - NE", "length": 4.0, "speed": 50.0, "lanes": 1, "param1": 3000.0, "param2": null, "param3": null, "road_type": 2, "source": 1, "target": 3 }, -
Problems Deploying Django, Gunicorn docker image to Kubernetes through rancher
I am having problems getting my docker image deployed on RKE. My docker image is a django application being served using gunicorn. I am using gitlab CI to test the app, build the container, and hold the container (in the gitlab container registry) it passes all the tests and builds the container successfully. When I go to deploy it on rancher it pulls the image just fine and builds the container but I keep getting an error that the gunicorn executable cannot be found. I have tried all the different types of configs for the CMD/ENTRYPOINT and I keep getting the error. Any help would be amazing as I am banging my head against the wall. Dockerfile is below: FROM python:3.8.5-slim-buster # install dependencies RUN apt-get -y update && apt-get -y upgrade && apt-get install -y musl-dev libpq-dev gcc ENV VIRTUAL_ENV=venv RUN python3 -m venv $VIRTUAL_ENV RUN echo $PATH ENV PATH="$VIRTUAL_ENV/bin:$PATH" RUN echo $PATH RUN ls -hal RUN pwd # Install dependencies: COPY requirements.txt . RUN pip install -r requirements.txt RUN ls -hal RUN ls -hal venv/bin RUN which gunicorn # copy project COPY . . EXPOSE 8080 CMD /venv/bin/gunicorn --bind :8080 django_app.wsgi Requirements.txt below (it is a bit messy … -
Two Ways to Handle a Request - Just Written Differently
I was looking at some different code on github and came across something that was confusing. Is there any differences between the code below? class RandomView(View): def get(self, *args, **kwargs): return render(self.request, 'random_template.html) Versus class RandomView(View): def get(self, request, *args, **kwargs): return render(request, 'random_template.html) To me this would do the same thing but to be fair my knowledge is pretty limited. Is one considered bad practice? Or maybe just preference? -
Django: Model relationship issues
I'm trying to get user invoices, expenses, withdrawals via celery tasks. After collecting all the data celery should send an email and etc... So the thing is that I've been stuck for a couple of days with the relationship that Django provides. I have missed a course about Django relationships, so I can't process it further. This is our project scheme: This is our models: class User(AbstractUser): username = None email = models.EmailField('email address', blank=True) phone = PhoneNumberField(unique=True) companies = models.ManyToManyField(Company, related_name='users') active_company = models.OneToOneField(Company, null=True, related_name='active_user', on_delete=models.SET_NULL) class InvoiceItem(BaseModel): objects = InvoiceItemManager() archives = InvoiceItemArchiveManager() invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE, related_name='invoice_items') item = models.CharField(max_length=255) class Invoice(Operation): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='invoices', null=True, blank=True) class Merchant(BaseModel): company = models.ForeignKey(Company, on_delete=models.PROTECT, related_name='merchants') name = models.CharField(max_length=255) company_code = models.CharField(max_length=255, default='', blank=True) def __str__(self): return f'{self.company} {self.name}' class Expense(Operation): category = models.CharField(choices=ExpenseCategories.get_choices(), default=ExpenseCategories.GENERAL.name, db_index=True, blank=True, max_length=255) merchant = models.ForeignKey(Merchant, on_delete=models.PROTECT, related_name='expenses', blank=True, null=True) class ExpenseReceipt(BaseModel): objects = ExpenseItemManager() archives = ExpenseItemArchiveManager() expense = models.ForeignKey(Expense, on_delete=models.CASCADE, related_name='receipts') This is what I've tried: # Get Invoices that were created in one week start_date = timezone.now() - timedelta(weeks=1) # .filter(created_at__range=(start_date, timezone.now()) invoices = InvoiceItem.objects.select_related('invoice').annotate( total_invoices=Sum('invoice'), ) -
Can a server execute a script (stored remotely on the server) on a client's machine?
Here's the entire desired process: I have a client-server architecture where the server is implemented using Django. The client (located outside the server's network): Connects to my server from a browser; Executes a script to package the images and other necessary files for the processing; Upload the packaged files to my server; My server processes the images; My server sends the processed images back to the client. My question is: can the server execute in anyway the script/executable that does the packaging on the client's machine? The script would be in Python or C. The main reason behind this question is that I want my script to remain on the server's side and I want to keep the client as thin as possible; I don't want to keep anything on the client's side except the package the script would generate and the returned data from the processing. I started looking into RPyC, but since I have very little insight into how I could do this, I am here gathering suggestions. -
How to set Heroku app to specific Postgres schema?
There is one database configured in Heroku. The Django application connects fine, but the tables are put in the public schema. These tables should be in the 'invoices' schema. That schema is already created, but it's empty. Below is what the settings.py currently look like: DATABASES["default"] = dj_database_url.config( conn_max_age=600, ssl_require=True, ) DB_SEARCH_PATH = os.environ.get("DB_SEARCH_PATH", "invoices") -
Django- Home Html gets empty list space while trying to print this team name as list
**Below is my code. Let me know how to get the team name alone printed View.py teams = {"P51AXX":"ECE","PZXXXXX":"Kafka","PAZZXXXX":"CDC","PDXXX":"HCC","PZIXXXX":"BDPaaS", "P18XXX":"API Gateway","PXXPXXX":"Stargate","PHHXXX":"Messaging Queue"} def home(request): list_teams = "" team_list = list(teams.values()) for team in team_list: #capitalized_team = team.capitalize() list_teams += f"<li><a href=>{team} </a><li>" data_1 = f"<ul>{list_teams}</ul>" return render(request,'home.html',{'data':data_1}) home.html : <!DOCTYPE html> <html> <body> <h1 style="text-align:center">PEP Metrics</h1> <p>Click the Below team to get Pagerduty counts</p> {{data|safe}} </body> </html> Image -
Django ORM Syntax for 'LIKE' queries with respect to Datetime
I have this table which has column "date" in the format "2021-03-12 08:12:44.350176". I want to compare a external date such as "2021-03-12 08:12:44" I have tried this new_date = datetime.datetime(2021, 3, 12, 8, 12, 44, tzinfo=<UTC>) obj = Test.objects.filter(date__contains=new_date).all() But it doesn't work, it returns empty sets. My goal is to fetch all the records against the new_date. Is there a way to remove milliseconds or way to compare the two dates? -
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?