Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Inserting POINT Geometry from DJANGO to POSTGIS database error
Hello I try to use DJANGO to insert point clicked on Leaflet in a POSTGIS database. During the import I receive the following error : "function st_geomfromewkb(bytea) does not exist" My understanding is that the ST_GeomFromEWKB is used to insert binary representation od geometry, and this is quite weird here because what I intend to do is inserting a wkb object. my view is defined as bellow: from django.contrib.gis.geos import Point def add_site(request): if(request.method == 'POST'): site_name = request.POST.get('site_name') customer_name = request.POST.get('customer_name') lat = str(request.POST.get('lat')) lng = str(request.POST.get('lng')) point = Point(lng,lat,srid=4326).wkb logger.info(type(point)) insert = customers_sites(site_name=site_name,customer_name=customer_name,geom=point) insert.save() Any idea of what is wrong here ?? Thank you for your help ! -
Grouping django "choices" dropdowns with ForeignKey?
I have a "delivery website" and I want to give it some styling. The order statuses are listed like this: ORDER_STATUS = ( ('Incoming',( ('PENDING', 'Pending'), )), ('Delivery',( ('OFD', 'Out for Delivery'), )), ('Finished',( ('CAN','Cancelled'), ('FIN','Delivered'), )) ) which, if you pass it to the "choices" for a charfield, makes a good looking grouped dropdown to select from. Is it possible to do the same, but with other Models(/classes)? I was thinking making a "TopStatus" and a "SubStatus" model, so I can give a "TopStatus" to every "SubStatus" (e.g. top status: 'incoming', sub status: 'pending'), but I have no idea on how I could nest these to look like the tuple above. If there's something similar in the original documentation, I'm sorry for missing that part! -
Sorting of search result items
How can I sort the search result so that when sorting by price, the program does not sort all the elements, but only the search result? (in views.py(#sort by price) I implemented price sorting, but it sorts all the items) views.py def filters(request): #search search_post = request.GET.get('search') if search_post: all = Product.objects.filter(Q(title__icontains=search_post) & Q(content__icontains=search_post)) else: all = Product.objects.all() #sort by price sort_by = request.GET.get("sort", "l2h") if sort_by == "l2h": all = Product.objects.all().order_by("price") elif sort_by == "h2l": all = Product.objects.all().order_by("-price") filters = IndexFilter(request.GET, queryset=all) context = { 'filters': filters } return render(request, 'index.html', context) filters.py import django_filters from .models import * class IndexFilter(django_filters.FilterSet): class Meta: model = Product fields = {'brand'} models.py class Product(models.Model): BRAND = [ ('apple', 'apple'), ('samsung', 'samsung'), ('huawei', 'huawei'), ('nokia', 'nokia'), ] img = models.URLField(default='https://omsk.imperiya-pola.ru/img/nophoto.jpg') title = models.CharField(max_length=80) brand = models.CharField(max_length=20, choices=BRAND) content = models.TextField() price = models.FloatField(default=1.0) def __str__(self): return self.title -
Why does a django gunicorn process call import on first API request?
Noticed if I do a print statement on a global level in the django level, it'll be called on the first API request, is there a way to run all global declarations before the first API? -
How to save MultipleChoiceField data using Django ModelForm
I'm trying to save data from a ModelForm that has MultipleChoiceFields. I want the user to be able to select multiple timeframes and have that data saved to the database. So far, when submitting the form using the MultipleChoiceField, I get nothing returned. Here's my models.py: class InfoFormModel(models.Model): YES_NO = ( ('yes', 'Yes'), ('no', 'No'), ) TIMEFRAME = ( ('1_weeks', '1 Week'), ('2_weeks', '2 Weeks'), ('3_weeks', '3 Weeks'), ('4_weeks_plus', '4 Weeks+'), ) PAGES_NEEDED = ( ('about_page', 'About Page'), ('contact_page', 'Contact Page'), ('blog_page', 'Blog Page'), ('map_page', 'Map Page'), ('ecommerce_page', 'Ecommerce Page'), ) brand_name = models.CharField( blank=False, null=False, max_length=500, default='') logo = models.CharField(choices=YES_NO, blank=False, null=False, max_length=500, default='no') what_is_the_service = models.TextField( blank=False, null=False, max_length=5000, default='') contact_number = models.BigIntegerField(blank=True, null=True, default='') email = models.EmailField(blank=True, null=True, max_length=300, default='') timeframe = models.CharField( choices=TIMEFRAME, max_length=100, blank=False, null=False, default='') aim = models.TextField(blank=False, null=False, max_length=5000, default='') products_product_images = models.CharField( choices=YES_NO, blank=False, max_length=500, null=False, default='') products_info = models.CharField( choices=YES_NO, blank=False, null=False, max_length=500, default='') pages_needed = models.CharField( choices=PAGES_NEEDED, blank=True, null=True, max_length=500, default='') def __str__(self): return self.brand_name forms.py: class InfoForm(forms.ModelForm): YES_NO = ( ('yes', 'Yes'), ('no', 'No'), ) TIMEFRAME = ( ('1_weeks', '1 Week'), ('2_weeks', '2 Weeks'), ('3_weeks', '3 Weeks'), ('4_weeks_plus', '4 Weeks+'), ) PAGES_NEEDED = ( ('about_page', 'About Page'), ('contact_page', 'Contact … -
Use request.session as the success_url in django
I have a CBV that I need to pass a request.session variable to as the success_url. I have not been able to implement this. May somebody help, please. class UpdateTeacherIssueView(LoginRequiredMixin,UpdateView): model = TeacherIssue form_class = UpdateTeacherIssueForm template_name = 'crud_forms/edit_teacher_issue.html' success_url =reverse_lazy('all', path = selected_item>) In function based views it would be, selected_item = request.session.get('item') How is the same possible in CBV? -
django-rest-knox - how to authenticate token for email verification?
I am trying to set-up email verification using django-rest-knox. The link is being sent out. When I use the following: from knox.auth import TokenAuthentication class VerifyEmailAPI(generics.GenericAPIView): def get(self, request): # Get the token from request # token = request.GET.get('token') # print(token) user = TokenAuthentication.authenticate(request, self) print(user) return Response({'message': 'Just testing for now'}) The url: http://127.0.0.1:8000/api/auth/email-verify/?token=58cab01ad07801dbe5e6c4fc5c6c7ef060bf7912cb723dc70e4c5fb677fbbf1e I get this error: AttributeError: 'VerifyEmailAPI' object has no attribute 'META' Complete traceback: Traceback (most recent call last): File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/views/generic/base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "/Users/sid/eb-virt/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Users/sid/eb-virt/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Users/sid/eb-virt/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Users/sid/eb-virt/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Volumes/coding/fort_dev/accounts/api.py", line 75, in get user = TokenAuthentication.authenticate(request, self) File "/Users/sid/eb-virt/lib/python3.8/site-packages/knox/auth.py", line 37, in authenticate auth = get_authorization_header(request).split() File "/Users/sid/eb-virt/lib/python3.8/site-packages/rest_framework/authentication.py", line 20, in get_authorization_header auth = request.META.get('HTTP_AUTHORIZATION', b'') AttributeError: 'VerifyEmailAPI' object has no attribute 'META' Am I doing something fundamentally wrong when using the django-rest-knox function? -
How to fetch data remotely for displaying into admin/index.html in django adminlte v3
I want to make api call and show data into django adminLTE home page. How can I achieve it? -
How to implement OneToTwo relation in django?
I want to implement a case where model A has exactly two B instances and model B has exactly one A instance. What is the best way to implement this? class A(Model): b1 = OneToOneField(B) b2 = OneToOneField(B) If I use this I have to provide two different related names to b1 and b2 fields. I want be able to simply say b.a_set.first() and get the object since I want B to have single A. And this is not really oneToTwo I think, b1 and b2 could point to the same B object. class B(Model): a = ForeignKey(A) If I use this then it is OneToMany, I want to be explicit about relation, and be able to use a.b1 and a.b2 What would be a good way to implement this? -
how to escape stretched-link in html block content
I am developing an app with Django and using bootstrap for the front end. Do you know how I can a "escape" a stretched-link in bootstrap ? In fact I like the behavior of having the total card being the link but the problem is that inside the card I have some tag that I want to be as link but it is like my stretched-link is covering all links in the card. Below is the snippet from bootstrap adapted to my needs <div class="row gx-5"> {% for post in post_list %} <div class="col-lg-4 mb-5"> <div class="card h-100 shadow border-0"> <img class="card-img-top" src="https://dummyimage.com/600x350/6c757d/343a40" alt="..." /> <div class="card-body p-4"> <a class="text-decoration-none link-dark stretched-link" href="{% url 'post-detail' post.id %}"><div class="h5 card-title mb-3">{{post.title}}</div></a> <p class="card-text mb-0">{{post.content}}</p> </div> <div class="card-footer p-4 pt-0 bg-transparent border-top-0"> <div class="d-flex align-items-end justify-content-between"> <div class="d-flex align-items-center"> <div class="small"> {% for tag in post.tag.all %} <a class="badge bg-secondary text-decoration-none link-light" href="{% url 'blog-index-tag' tag.tag_name %}">{{tag}}</a> {% endfor %} <div class="text-muted">April 2, 2022</div> </div> </div> </div> </div> </div> </div> {% endfor %} </div> -
Deploying in production gunicorn + nginx with domain
I'm new to development and my trying to deploy my django app with gunicorn and nginx. I've followed this tuto and tried to understand every step. https://www.agiliq.com/blog/2013/08/minimal-nginx-and-gunicorn-configuration-for-djang/ I bought a domain at namecheap. I think a missed a step, I don't know where. When I try to access the adress I'can't. I have 2 files inside /etc/nginx/sites-enabled/ | mjc and mjcpublic Here the content MJC server { listen localhost:8000; location / { proxy_pass http://127.0.0.1:8001; } location /static/ { autoindex on; alias /home/webserver01/ProjetE2I/TableauDeBordMjc/src/static/; }} mjc public listen 80; server_name mjc-internal-stcham.me www.mjc-internal-stcham.me; location / { proxy_pass http://127.0.0.1:8001; } location /static/ { alias /home/webserver01/ProjetE2I/TableauDeBordMjc/src/static; } Thank you for your help. -
Graphene/Django mutations return null
I created the following model in my django app: class Post(models.Model): title = models.CharField(max_length=125, unique=True) slug_title = models.SlugField(max_length=255, unique=True) body = models.TextField() published_date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) status = models.BooleanField(default=False) class Meta: ordering = ['-published_date'] def __str__(self): return self.title def save(self, *args, **kwargs): self.slug_title = slugify(self.title) super(Post, self).save(*args, **kwargs) I want to be able to use an API to do POST/GET requests later on, so I decided to use graphene-django. Everything is installed properly and working. As per the tutorials, I created my schema.py file as follow: # define schema class PostType(DjangoObjectType): class Meta: model = Post fields = ('title', 'body', 'author', 'published_date', 'status', 'slug_title') class UserType(DjangoObjectType): class Meta: model = get_user_model() class PostInput(graphene.InputObjectType): title = graphene.String() slug_title = graphene.String() body = graphene.String() author = graphene.Int() published_date = graphene.DateTime() status=graphene.Boolean() class CreatePost(graphene.Mutation): class Arguments: input = PostInput(required=True) post = graphene.Field(PostType) @classmethod def mutate(cls, root, info, input): post = Post() post.title = input.title post.slug_title = input.slug_title post.body = input.body post.author = input.author post.published_date = input.published_date post.status = input.status post.save() return CreatePost(post=post) class Query(graphene.ObjectType): all_posts = graphene.List(PostType) author_by_username = graphene.Field(UserType, username=graphene.String()) posts_by_author = graphene.List(PostType, username=graphene.String()) posts_by_slug = graphene.List(PostType, slug=graphene.String()) def resolve_all_posts(root, info): return Post.objects.all() def resolve_author_by_username(root, info, username): return User.objects.get(username=username) … -
How to get email address of all users in Django
I am learning django and I am stuck with this problem. How do I get the email address of all the users in Django. The user can be of any type like superuser, general user etc. I tried the following but I am not getting email address of all the users. user = User.objects.get(id=2) user_email = user. Email print(user_email) I want something like a list of all the email addresses. Can someone please help me with it? -
Django reset model fields to their default value?
On refresh I want this to reset to default from_date = models.DateField(default='2000-01-01') Status = models.CharField(choices=A_K, max_length=100, default='no Status') to_date = models.DateField(default='2000-01-01') right now I have default when something new is created, while it is fine, I need it to be set to default if page is refreshed. I read here: Django - How to reset model fields to their default value? that it is possible with none like with null=true and blank=true, but that didnt worked. Do I really need a whole function for that ? -
how to create a sharable link for a card in django template
I am learning to create a blogging website in Django web framework where i am displaying my blog header and small body content in a card for every blog in blog list page, And i am trying to create a sharable link for every card so that if somebody share that link to another website it display the whole card itself. -
Plausible analytics on a server with a webapp
I have Django hosted with Nginx on DigitalOcean. Now I want to install Plausible Analytics. How do I do this? How do I change the Nginx config to get to the Plausible dashboard with mydomain/plausible for example? -
get_absolute_url is not working--gives this error NoReverseMatch error
I get this error when trying to user get_absolute_url--what i am doing wrong? NoReverseMatch at /mega_archive/books/ Reverse for 'book' with arguments '('',)' not found. 1 pattern(s) tried: ['mega_archive/book/(?P<book>[-a-zA-Z0-9_]+)/\\Z'] views.py def books(request): books = Book.objects.all() return render(request, 'mega_archive/books.html',{ 'books':books }) def book(request, book): book = get_object_or_404(Book, slug=book) return render(request, 'mega_archive/book_details.html', { 'book':book }) urls.py path('books/', views.books, name='books'), path('book/<slug:book>/', views.book, name='book'), models.py def get_absolute_url(self): return reverse('mega_archive:book', args=[self.slug]) def __str__(self): return self.title html {% for book in books %} <a href="{{book.get_absolute_url}}">{{book}}</a><br> {% endfor %} can anyone point to what I did wrong? -
Deploy a DJANGO application on HEROKU without migrate
I want to deploy my django application on heroku But heroku runs manage.py migrate I would like heroku not to launch any command, how can I do? -
why my Django debug tool bar is not showing in the browser?
I perfectly followed all the steps in this documentation : https://django-debug-toolbar.readthedocs.io/en/latest/installation.html and tried these solutions I found online adding to the settings module: if DEBUG: import mimetypes mimetypes.add_type("application/javascript", ".js", True) def show_toolbar(request): return True DEBUG_TOOLBAR_CONFIG = { 'SHOW_TOOLBAR_CALLBACK': show_toolbar, } if DEBUG: import socket # only if you haven't already imported this hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ ip[: ip.rfind(".")] + ".1" for ip in ips] + ["127.0.0.1", "10.0.2.2"] but no luck any suggestions? -
Using both Django template and React
Hi guys I’m trying to bulid a website which django works as an rest-api and react works as a front side. I manage to do the whole thing just fine and about to deploy it using aws. But there is one thing I couldn’t really get. Inside my django project I have an app that uses only django template to render things to front. And other apps are working only as apis to get and post things via react. Is it possible to deploy this kind of structure without any special options? I searched internet for a while but I couldn’t really find an example that fits my situation. Thanks! -
How can I resize my video in Django using MoviePy and Dropzone?
I want to limit the length of the uploaded videos to one minute, I have tried to use MoviePy but so far I have not been able to do it. Can you help me please ? models.py enter image description here views.py enter image description here My error enter image description here -
Django JSON field - query id field
I am trying to filter a Django JSONfield (MariaDB backend, Django 4.0) target_360 is the JSON field, every query I've tried brings back an empty queryset, even though the debug statement clearly shows the matching id in the first row of the 'parent' query field in models.py using django.models.JSONField target_360 = models.JSONField(_('360 target'),default=None, null=True) Query Code surveys_with_target = Survey_Instance.objects.filter(pulse_id=pulse_id, survey_id=survey_id, target_360__isnull=False) logger.debug('First row target_360') logger.debug(surveys_with_target[0].target_360) logger.debug('target_id in filter') logger.debug(target_id) survey_test = surveys_with_target.filter(target_360__contains=target_id) logger.debug("SURVEY TEST:") logger.debug(survey_test) survey_test = surveys_with_target.filter(target_360__id__contains=target_id) logger.debug("SURVEY TEST 2:") logger.debug(survey_test) survey_test = surveys_with_target.filter(target_360__id=target_id) logger.debug("SURVEY TEST 3:") logger.debug(survey_test) debug output: First row target_360 {"id": "189f5422-f522-4860-8794-a3375f84a086", "target_type": "Individual"} target_id in filter 189f5422-f522-4860-8794-a3375f84a086 SURVEY TEST: <QuerySet []> SURVEY TEST 2: <QuerySet []> SURVEY TEST 3: <QuerySet []> It's probably something really simple, what at I am doing wrong? -
problem setting my python/django project up in docker
I am having a problem setting my python/django project up in docker. I ran docker build . and it ran OK to the end with no errors. My source code is in my Z: drive is /ISICSFLSYN01/ISICSFLSYN01 which is my synology NAS. When I run the docker-compose.yml, I get the following message "mount path must be absolute". How do I get docker-compose to see the code in my NAS? docker-compose.yml version: "3.9" services: web: build: . ports: - "8000:8000" command: python manage.py runserver 0.0.0.0:8000 volumes: - .:"/ISICSFLSYN01/ISICSFLSYN01/Django Projects/code" running Z:\Django Projects\code>docker-compose up [+] Running 0/0 Container 7bc5f2ff15b2_7bc5f2ff15b2_7bc5f2ff15b2_code-web-1 Recreate 0.1s Error response from daemon: invalid volume specification: '/run/desktop/mnt/host/uC/ISICSFLSYN01/ISICSFLSYN01/Django Projects/code:"/ISICSFLSYN01/ISICSFLSYN01/Django Projects/code":rw': invalid mount config for type "bind": invalid mount path: '"/ISICSFLSYN01/ISICSFLSYN01/Django Projects/code"' mount path must be absolute Z:\Django Projects\code> My directories are set up: Z:\Django Projects\code> .venv .vs django_project pages .dockerignore db.sqlite3 docker-compose.yml dockerfile manage.py requirements.txt -
Heroku application error whentrying to deploy django project
i'm trying to deploy my django project on heroku. The deployment is successful but then if I try to go to my project page I get the following error: Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail This is my deployment log: -----> Building on the Heroku-22 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt -----> No change in requirements detected, installing from cache -----> Using cached install of python-3.10.7 -----> Installing pip 22.2.2, setuptools 63.4.3 and wheel 0.37.1 -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput 130 static files copied to '/tmp/build_fe9a8caa/staticfiles', 384 post-processed. -----> Discovering process types Procfile declares types -> realease, web -----> Compressing... Done: 29.5M -----> Launching... Released v4 https://appname.herokuapp.com/ deployed to Heroku -
Django DISTINCT and get all the objects from the distinct value
Can someone here help me with this problems ? struggling so long and can't get it right. Suppose I have this database: id Referall Code User Email Date of Using ______________________________________________________________________ 1 ABCD John john@email.com 13-06-2022 2 EFGH Marry marry@email.com 17-06-2022 3 IJKL Bryan bryan@email.com 21-06-2022 4 ABCD Luke luke@email.com 05-07-2022 5 EFGH Tom tom@email.com 11-08-2022 What I want the result will be like this: Referall Code User Email Date of Using _______________________________________________________________ ABCD John john@email.com 13-06-2022 Luke luke@email.com 05-07-2022 EFGH Marry marry@email.com 17-06-2022 Tom tom@email.com 11-08-2022 IJKL Bryan bryan@email.com 21-06-2022 I am using sqLite as a database, and can't find a way to get it done in django. Thanks in advanced