Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and AWS S3 returns This backend doesn't support absolute paths
I am working on a Django project whereby when users register their profiles get automatically created using the signals.py. Everything works fine in the localhost, but now I want to migrate to the AWS S3 bucket before deploying my project to Heroku. After configuring my AWS settings in settings.py, I get the error NotImplementedError: This backend doesn't support absolute paths. after trying to create a superuser through the python manage.py createsuperuser command. Here is my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='default.jpg', null=True, blank=True) bio = models.TextField() resume= models.FileField('Upload Resumes', upload_to='uploads/resumes/', null=True, blank=True,default='resume.docx') Here is the signals.py: @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() And here is my settings.py; # S3 BUCKETS CONFIG AWS_ACCESS_KEY_ID='' AWS_SECRET_ACCESS_KEY='' AWS_STORAGE_BUCKET_NAME='' # Storages configuration AWS_S3_FILE_OVERWRITE= False # AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # Only public read for now AWS_QUERYSTRING_AUTH = False AWS_DEFAULT_ACL='public-read' STATIC_URL = '/static/' Inside the s3 bucket, I have the default.jpg and resume.docx in the root folder. Any assistance will be highly appreciated. Thanks. -
How to test all Object values in a python function
I would like to test all x values in this function, without calling each x value ( x[0] ...), so a kind of x[n] or ' for all values of x'. And to list all TickerZ values in a list depending on if the x value passed the IF statement. room = str('Bingo Bango Bungo EURUSD=X') x = room.split() def Symbol(symbol): aapl = yf.Ticker(symbol) ainfo = aapl.history(period='1y') if len(ainfo) >= 40: print('yes it is a symbol') global tickerZ tickerZ = symbol new_Memory = Memory.objects.create(user=current_user, raw_message=room, date1=datemin, date2=datemax, ticker=tickerZ, command=cmd_exec) new_Memory.save() return tickerZ symb1 = Symbol(x[0]) symb2 = Symbol(x[1]) symb3 = Symbol(x[2]) symb4 = Symbol(x[3]) Code explanation: So basically, i have a string, i'm splitting it into words, which represent all x values. In this case x[0] is Bingo. I'm passing all x's into a IF statement to filter the relevant x values. I know if a x is relevant if TickerZ has a value, because the variable is defined after the filter. -
How to make Django redirect to other page?
I have an app named "works" where all my works should contain. There are cards-previews to my works. So I want them clickable and redirecting to the work that is clicked and soon shown the html file of the work. The problem is in redirecting to that work. In myapp/urls.py is the following urlpatterns = [ path("", WorksView.as_view(), name="works"), path("<slug:work_slug>/", WorkDetailView.as_view(), name="work-detail"), ] myapp/models.py class Works(models.Model): -- other attributes -- slug = models.SlugField( null=False, db_index=True, blank=False, max_length=255, unique=True, verbose_name="URL", ) def get_absolute_url(self): from django.urls import reverse return reverse("work-detail", kwargs={"work_slug": self.slug}) So what class based view should be used in myapp/views.py for WorkDetailView? I have tried View, TemplateView, RedirectView, but neither of them work properly that I want to. The last try was that: class WorkDetailView(View): def get(self, request, *args, **kwargs): work = get_object_or_404( Works, slug=kwargs["work_slug"] ) print(work.get_absolute_url()) return render(request, work.get_absolute_url(), {"works_data": work}) The work.get_absolute_url works good, but Django cant find template My project folder: But when I change the return string to return render(request, f"{work.get_absolute_url()[1:-1]}.html", {"work": work}) it works and prints "works/not-found/", but I dont think that it is the correct way So how can I do it right? The last try was to make that using View but Django … -
Django signals / notification system
Is it a good aproach to use Django signals to implement email notification system? I have CustomUser model related with CustomUserPreferences planned as follows: class CustomUserPreferences(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, default=None, on_delete = models.CASCADE, primary_key = True) lesson_notification = models.BooleanField(default=True) journal_notification = models.BooleanField(default=False) login_notification = models.BooleanField(default=False) excercise_notification = models.BooleanField(default=False) homework_notification = models.BooleanField(default=True) class CustomUser(AbstractUser): ... email = models.EmailField(_('email address'), unique=True) preferences = models.OneToOneField(CustomUserPreferences, null = True ,default=None, on_delete = models.CASCADE) students = models.ManyToManyField(to = 'self', related_name = 'teachers', symmetrical = False, blank = True) Whenever a new object of lets say Lesson is created I want to send an email to the user and that's fine - becaouse it won't overload any server. The question is: will it pay off to use signals for a list of users that contains lets say 100s or 1000s of users? I'm afraid it will slow down the whole application. Is there any other "clear and elegant" way to do this? Django docs advices not to use signals whenever it's possible. -
api call method and viewset
I try to create a api call: class CategoryViewSet(viewsets.ModelViewSet): serializer_class = CategorySerializer queryset = Category.objects.all() @action(methods=['get'], detail=False) def mainGgroups(self,request): mainGroups = Category.objects.filter(category_id__isnull=True) serializer = self.get_serializer_class()(mainGroups) return Response(serializer.data) serializer: class CategorySerializer(serializers.ModelSerializer): animals = AnimalSerializer(many=True) class Meta: model = Category fields = ['id','category_id','name', 'description', 'animals'] So the main url works: http://127.0.0.1:8000/djangoadmin/groups/ But if I go to: http://127.0.0.1:8000/djangoadmin/groups/maingGroups/ I get this error: { "detail": "Not found." } urls.py: router = routers.DefaultRouter() router.register('groups', CategoryViewSet) urlpatterns = [ path('', include(router.urls)) ] and urls.py of admin looks: from django.contrib import admin from django.urls import path, include urlpatterns = [ path("djangoadmin/", include('djangoadmin.urls')), path("admin/", admin.site.urls), ] Question: how to create api method in main url? -
I have created a django ModelForm that is not showing up in my html template, I am trying to determine why that code is not rendering my form?
models.py from django.db import models # Create your models here. class Subscriber(models.Model): """A subscriber Model""" email = models.CharField(max_length=255, blank=False, null=False, help_text="Subscriber Email Address", unique=True) full_name = models.CharField(max_length=100, blank=False, null=False, help_text="First and Last Name") class Meta: verbose_name = "Subscriber" verbose_name_plural = "Subscribers" forms.py from django.forms import ModelForm from .models import Subscriber class SubscriberForm(ModelForm): class Meta: model = Subscriber fields = ["email", "full_name"] views.py from django.shortcuts import render from .forms import SubscriberForm from django.http import HttpResponseRedirect from django.contrib import messages # Create your views here. def subscriber(request): if request.method == "POST": subscriber_form = SubscriberForm(request.POST or None) if subscriber_form.is_valid(): subscriber_form.save() messages.success(request, "") return HttpResponseRedirect("/") else: subscriber_form = SubscriberForm() context = { "form_subscriber": subscriber_form } return render(request, "subscriber/subscriber_form.html", context) subscriber_form.html {% block content %} <div> <form method="POST"> {% csrf_token %} {{ subscriber_form.as_ul }} <input type="submit" value="Submit"> </form> </div> {% endblock %} Only my submit button is publishing, however the form is never showing up for me. I have followed the django docs exactly and still am not getting any good results. -
how to call a function as a context in django
class User(AbstractUser): GENDER_STATUS = ( ('M', 'Male'), ('F', 'Female') ) address = models.TextField(null=True, blank=True) age = models.PositiveIntegerField(null=True, blank=True) description = models.TextField(null=True, blank=True) gender = models.CharField(max_length=1, choices=GENDER_STATUS, null=True, blank=True) phone = models.CharField(max_length=15, null=True, blank=True) def get_full_name(self): return f'{self.first_name} {self.last_name}' i declare a function get_full_name and then i want too call it in my view and show it in my template. this is my view from django.shortcuts import render from accounts.models import User def about_us(request): fullname = User.get_full_name context = { 'fullname': fullname } return render(request, 'about_us.html', context=context) and this is my template as you can see i used a loop for my context <div class="container"> <div class="d-flex flex-wrap justify-content-around"> {% for foo in fullname %} <p>{{ foo }}</p> {% endfor %} </div> </div> but i cant get the get_full_name parameters in my template as value too show. i'll be more than happy if sombodey help me. THANK YOU! -
Cannot assign "OrderItem.product" must be a "Product" instance
I am trying to create a "create order" endpoint, i keep getting Cannot assign "<django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7f50dad00f70>": "OrderItem.product" must be a "Product" instance. heres my models def product_images(instance, filename): return f"product/{instance.product_name}/{filename}" class Product(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=200, null=True, blank=True) description = models.TextField() date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) image = models.ImageField( storage=MediaRootS3BotoStorage(), upload_to="product_images", null=True, blank=True, ) price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name def save(self, *args, **kw): self.slug = slugify(f"{self.name}") super(Product, self).save(*args, **kw) # Ecommerce Models Store and Product def store_images(instance, filename): return f"{instance.store_name}/{filename}" class Store(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=200, null=True, blank=True) description = models.TextField() date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) image = models.ImageField(upload_to="store_images", null=True, blank=True) delivery_fee = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) address = models.CharField(max_length=100, null=True, blank=True) phone_number = models.CharField(max_length=100, null=True, blank=True) products = models.ManyToManyField("Product", through="StoresProduct") def __str__(self): return self.name def save(self, *args, **kw): self.slug = slugify(f"{self.name}") super(Store, self).save(*args, **kw) class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ManyToManyField("Product", through="StoresProduct") quantity = models.IntegerField(default=1) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.user.email def get_total(self): return self.product.price * self.quantity class StoresProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) seller = models.ForeignKey(Store, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) quantity = models.IntegerField(blank=True, null=True) date_created … -
Django printing variable in template that has been passed to it in python
I am trying to get 'date' which can be eg 2023/01/29 to print in my template file. def time_booking(request): if 'date' in request.COOKIES: context = { 'date':request.COOKIES['date'], } print("Run Run") return render(request, "path_to_file.html", context) <h1>Date will be here here</h1> {% if date != -1 or null %} <h1> Date is real {{date}}</h1> {% else %} <h1> Date is not real{{date}} </h1> {% endif %} <h1> complete run </h1> The code currently check if the variable 'date' exists and isn't -1 but I then go to print it and the content doesn't come out. I tried using a single set of {} as well as using print(content[date]), but again the variable was not output. I am trying to get it to output the date which has been entered before hand. Any help would be greatly apricated. -
Static Files not loading when DEBUG = False
I'm using namecheap shared hosting and I hosted my site using cpanel. My site is working fine but if i made DEBUG = False in project settings.py file the static files are not loading. My site url: https://drshahidabegum.com/ settings.py ----------- # Static files (CSS, JavaScript, Images) STATIC_DIR = [ BASE_DIR / "static", ] STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py in project folder ------------------------- """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('dr_shahida.urls')), ] # Configure Admin Titles admin.site.site_header = "DR. Shahida Begum" admin.site.site_title = "DR. Shahida Begum" admin.site.index_title = "Welcome to Admin Dashboard" handler404 = 'dr_shahida.views.error_404_view' urls.py in app folder ------- from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.index, name='index'), path('testimonial/', views.testimonial, name='testimonial'), path('contact/', views.contact, name='contact'), path('blog/', views.blog, name='blog'), path('blog/post/<int:post_id>', views.blogdetailview, name='blogdetailview'), path('set_language/<str:ln>', views.set_lang, name='set_lang'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I want my static files to work when DEBUG = False in project settings.py file. -
Truly dynamic DateField values in Django
Some of my app models define date ranges (e.g. of contracts), where the current instance has no fixed end date (i.e. it should always evaluate to today). Setting the default parameter on the end field – class Contract(models.Model): building = models.ForeignKey(Building, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) begin = models.DateField() end = models.DateField(default=datetime.date.today) – will populate the field with a fixed value. A property to work around the problem – class Contract(models.Model): building = models.ForeignKey(Building, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) begin = models.DateField() end = models.DateField(blank=True) @property def get_end(self): if not self.end: return datetime.date.today() return self.end – does not work with querysets. Is there any way to implement a truly dynamic value on the database level using Django's ORM? -
Django-graphene query sorting is not working
I have model Event which I want to sort by event_datetime column in resolver, but it doesn't work. My Event model looks like this: class Event(models.Model): name = models.CharField(db_index=True, max_length=255) event_type_id = models.ForeignKey(EventType, on_delete=models.PROTECT, default='friendly match', related_name='events_by_type') city = models.CharField(max_length=255, db_index=True, blank=False) country = models.CharField(max_length=255) place_id = models.ForeignKey(Place, on_delete=models.SET_NULL, null=True, related_name='events_by_place') event_datetime = models.DateTimeField() tournament_id = models.ForeignKey(Tournament, on_delete=models.PROTECT, blank=True, null=True, related_name='events_by_tournament') description = models.TextField(blank=True) organizer = models.ForeignKey(User, on_delete=models.PROTECT, related_name='organizer', blank=True) participants = models.ManyToManyField(User, blank=True, related_name='events_by_participant') creation_datetime = models.DateTimeField(auto_now_add=True, editable=False) update_datetime = models.DateTimeField(auto_now=True) And my Query object looks like this: class Query(graphene.ObjectType): events_by_organizer = graphene.List(EventType, id = graphene.ID(required=True)) def resolve_events_by_organizer(root, info, id): try: return Event.objects.filter(organizer=id).order_by('-event_datetime') except Event.DoesNotExist: return None In graphQL I get events query without sorting by event_datetime. How can I sort query in Django-graphene? -
How to fix django.db.utils.OperationalError: (1046, 'No database selected')
I have a column problem in the database when the yak uses python manage.py migrate. I want to write code to use DATABASE_URL in docker-compose.yml, how should I solve it? I've experimented with writing these codes. Can you advise me a bit? mysql> show databases; +--------------------+ | Database | +--------------------+ | DatabaseUBU | | information_schema | | mariadb | | mydb | | mysql | | performance_schema | | sys | +--------------------+ 7 rows in set (0.02 sec) mysql> create database mariadb; ERROR 1007 (HY000): Can't create database 'mariadb'; database exists docker-compose.yml version: '3.7' services: db: image: mariadb:10 command: --default-authentication-plugin=mysql_native_password restart: always environment: - MYSQL_ROOT_PASSWORD=mariadb - MYSQL_DATABASE=mariadb - MYSQL_USER=mariadb - MYSQL_PASSWORD=mariadb - MARIADB_ROOT_PASSWORD=mysecretpassword ports: - 3306:3306 volumes: - "mysqldata:/var/lib/mysql" web: build: . restart: always command: python manage.py runserver 0.0.0.0:8000 environment: - DATABASE_URL=mariadb+mariadbconnector://user:mariadb@db:3306/mariadb ports: - "8000:8000" depends_on: - db volumes: mysqldata: setting.py import dj_database_url import os DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', **dj_database_url.config(default=os.environ.get('DATABASE_URL')) } } -
How to write to Django FileField from a tempfile?
I am processing an image within a Django app. I used rasterio to process the geospatial image. I want to save the output directly to a FileField in a Model. I used a tempfile to write the output from rasterio, and used the method Model.FileField.save to hopefully write it with a reference to my Model instance. I have a simple model: class MaskedLayer(models.Model): name = models.CharField(max_length=250, blank=True) file = models.FileField( upload_to='masked', null=True, max_length=500) In my tasks, however this is an example: from celery import shared_task import rasterio import tempfile from app.models import MaskedLayer @shared_task def process_image(): mask_layer_name = 'processed_image.tif' masked_layer = MaskedLayer.objects.create() with rasterio.open('example.tif') as dataset: # only example of reading/processing of image out_image = dataset.read() with tempfile.NamedTemporaryFile() as tmpfile: tmpfile.write(out_image) with rasterio.open(tmpfile.name) as dataset: masked_layer.file.save(mask_layer_name, File(dataset)) pass I get this response. I am not sure of the error. Feel free to use the example file. Fatal Python error: Segmentation fault Current thread 0x00007f453b463740 (most recent call first): File "/usr/local/lib/python3.11/site-packages/django/views/debug.py", line 232 in get_traceback_frame_variables File "/usr/local/lib/python3.11/site-packages/django/views/debug.py", line 544 in get_exception_traceback_frames File "/usr/local/lib/python3.11/site-packages/django/views/debug.py", line 490 in get_traceback_frames File "/usr/local/lib/python3.11/site-packages/django/views/debug.py", line 320 in get_traceback_data File "/usr/local/lib/python3.11/site-packages/django/views/debug.py", line 403 in get_traceback_text File "/usr/local/lib/python3.11/site-packages/django/utils/log.py", line 125 in emit File "/usr/local/lib/python3.11/logging/init.py", line 978 in handle … -
VS Code + Pylance does not find venv-installed modules while venv is activated
I use VS Code Version: 1.74.3 on MacOS 13.2. python -V returns Python 3.11.1. I get the following error message: Import "django.shortcuts" could not be resolved from source Pylance(reportMissingModuleScource). As you can see in the screenshot, the correct venv is activated and includes Django. I checked also these threads: Import could not be resolved/could not be resolved from source Pylance in VS Code using Python 3.9.2 on Windows 10 and https://stackoverflow.com/a/65802367/2321643 but the suggested solution with reloading the windows did not help. Using Debug I can safely run my Django-application without any import issues. What do I need to do that Pylance does not issues these problems? -
Override response in Django Rest Framework serializer
I have a serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'name') And view: class UserListView(ListAPIView): model = User serializer_class = UserSerializer And as expected on a GET request i get a response like [ { "id": "1", "name": "First", }, { "id": "2", "name": "Second", } ] What should i change to get response like this: [ 'users': [ { "id": "1", "name": "First", }, { "id": "2", "name": "Second", }] ] I think it's easy, but can't understand how. -
how to extract the folder from zip file in upload with html and javascript and django
I am working on a django app in which the html code called tool.hmtl along with the javascript code called myscripts.js let the user upload the folder and then do some processing on that data. Relevant section of tool.hmtl is given as follows. <main class="tool mg-t-900"> <div id="folderUploadDiv"> <h1 class="tool__heading | text-center text-capitalize"> Upload your folder here </h1> <label for="folder" class="tool__upload | flex flex-center flex-column mg-t-500 text-center" > <i class="ri-upload-cloud-line tool__icon"></i> <p class="tool__txt text-capitalize">Browse folder to upload</p> </label> <input type="file" id="folder" webkitdirectory multiple /> .............some code...... <script src="{% static 'myscripts.js' %}"></script> <script src="{% static 'app.js' %}"></script> <script> const fileInput = document.querySelector("#folder"); const loder = document.querySelector(".loder"); const toggleLoder = function () { loder.classList.add("active"); setTimeout(() => { loder.classList.remove("active"); }, 30000); startTypingAnimation(); }; fileInput.addEventListener("change", toggleLoder); function startTypingAnimation() { new TypeIt("#loder-text", { strings: "Your file is being prepared...", speed: 75, loop: true, }).go(); } </script> <script> setTimeout(function () { location.reload(); }, 300000); // refresh every 5 minutes (300000 milliseconds) </script> </body> </html> {% endblock %} and relevant section of myscripts.js is as under. // const axios = require('axios'); $("#folderUploadDiv").show(); $("#selectorDiv").hide(); username = ""; contentType = ""; var dataToSend = [] var flag=1 document.getElementById("folder").addEventListener("change", function(event) { var output = document.querySelector("ul"); var files = event.target.files; var … -
How can I write function in views.py using rest_framework
I want to processing posted api data in views.py. How can I do it. I am getting error. My views.py: from django.shortcuts import render, redirect from rest_framework import viewsets from rest_framework.decorators import api_view from rest_framework.response import Response from .models import Student, Teacher from .serializer import StudentSerializer, TeacherSerializer class StudentView(viewsets.ModelViewSet): @api_view(['GET', 'POST']) def index(self,request): if request.method == 'GET': queryset = Student.objects.all() serializer_class = StudentSerializer elif request.method == 'POST': pass class TeacherView(viewsets.ModelViewSet): queryset = Teacher.objects.all() serializer_class = TeacherSerializer My urls.py: from django.contrib import admin from django.urls import path, include from students import views from rest_framework import routers router = routers.DefaultRouter(trailing_slash = False) router.register(r'studentdetails', views.StudentView, basename='studentdetails') router.register(r'teacherdetails', views.TeacherView, basename='teacherdetails') urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)) ] when I'm opening http://localhost:7777/studentdetails I'm getting error: 'StudentView' should either include a queryset attribute, or override the get_queryset() method. How can I write it correct? -
How can I move an image element on the x-axis at keypress with Javascript?
In my Django project, I have a "sprite" which is an image element in the HTML template. I want to make a small interactive game on the page when clicked on "A" key, the image will move on the x-axis. How can I achieve that with JavaScript? I tried to change the offsetLeft value using .offsetLeft and the x position value by updating the .style attribute but couldn't manage it both ways. contact.html: {% load static %} {% block script %} <script src="{% static 'potbs/contact.js' %}"></script> {% endblock %} {% block body %} <div class="col"> <img src="media/images/phone.png" alt="phone" class="rounded floar-start"> <img src="media/images/stick.png" class="rounded float-end" id="sprite" alt="..." style="margin-top:100px;"> <img src="media/images/wasd.png" class="rounded float-end" id="wasd" alt="..." style="margin-top:100px;display: none;"> <button class="btn btn-primary float-end" id="start">Start</button> </div> {% endblock %} contact.js: document.addEventListener("DOMContentLoaded", function(){ const button = document.getElementById("start"); const wasd = document.getElementById("wasd"); const sprite = document.getElementById("sprite"); button.onclick = function(){ button.style.display = "none"; wasd.style.display = "block" document.addEventListener("keypress",function(event){ if(event.key == "a"){ wasd.style.display = "none"; sprite.offsetLeft = sprite.offsetLeft + 10; } }); }; }) -
How to return values that are NULL in database with Django?
I hava a django app and I try to write some api calls. So I have one table And I want to return the values where category_id is null. So this sql statement works: SELECT * FROM public.djangoadmin_category where djangoadmin_category.category_id is null ORDER BY id ASC returns as output: 11 "zoogdieren" "zoogdieren" "hoi" "photos/categories/1_eDJtmdP.jpg" "2023-01-27 18:25:18.624272+01" "2023-01-27 18:25:18.624272+01" 12 "amfibieen" "amfibieen" "kujhkjh" "photos/categories/1_KJDTBPc.jpg" "2023-01-27 18:25:38.444066+01" "2023-01-27 18:25:38.444066+01" 13 "vogels" "vogels" "kljhkjh" "photos/categories/1_FGkA44b.jpg" "2023-01-27 18:26:00.390812+01" "2023-01-27 18:26:00.390812+01" 21 "reptielen" "reptielen" "reptielen" "photos/categories/1_EoVggfL.jpg" "2023-01-27 18:55:04.565339+01" "2023-01-27 18:55:04.565339+01" 23 "schildpadden" "schildpadden" "schildpadden" "photos/categories/1_RkKQ5md.jpg" "2023-01-27 18:55:51.724641+01" "2023-01-29 12:40:45.014174+01" But now I want to write a API call for it, so that I can use it for the frontend. the model: from django.db import models class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100) description = models.TextField(max_length=1000) images = models.ImageField(upload_to="photos/categories") category = models.ForeignKey( "Category", on_delete=models.CASCADE, related_name='part_of', blank=True, null=True) date_create = models.DateTimeField(auto_now_add=True) date_update = models.DateTimeField(auto_now=True) class Meta: verbose_name = "category" verbose_name_plural = "categories" def __str__(self): return self.name urls.py: from django.urls import path, include from rest_framework import routers from .views import CategoryViewSet router = routers.DefaultRouter() router.register('categories', CategoryViewSet) urlpatterns = [ path('', include(router.urls)) ] serializer: from rest_framework import serializers from .models import Animal, Category class CategorySerializer(serializers.ModelSerializer): animals = AnimalSerializer(many=True) … -
ModuleNotFoundError: No module named 'poststaggit' --- How do I make error?
ModuleNotFoundError: No module named 'poststaggit' ModuleNotFoundError: No module named 'poststaggit' -
Django with Bootsrap treeview
I’m trying to create a page to show a folder and its content using Tree-view Bootstrap. The folder may contain many sub-folders and files (child nodes). I want to implement one of those examples in a Django application. Bootstrap Tree-views page Let's say this one Animated Tree-views. where my model is: class Document(models.Model): Title = models.CharField(max_length=150) SHRPath = models.FileField(upload_to='Document/', validators= [validate_file_size]) def __str__(self): return self.Title and the views.py: def FileTree(request): documents = Document.objects.all()[:100] tree_data = [] for document in documents: shr_path_string= str(document.SHRPath) parents = shr_path_string.split('/') nodes = [{"text": parent} for parent in parents] tree_data.append({"text": document.Title, "nodes": nodes}) context = { 'tree_data': tree_data, } return render(request, 'filetree.html', context) and the HTML page is: <!DOCTYPE html> <div id="treeview"></div> <script> let data = {{ tree_data|safe }}; $(document).ready(function() { console.log("Tree data:", data); $('#treeview').treeview({ data: data, }); }); </script> <!-- jQuery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- Bootstrap Treeview CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.css"> <!-- Bootstrap Treeview JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.js"></script> This it doesn’t work however and it shows a blanc page!. Then to check if the data is rendered to the page I checked it by adding this code to page and its ok. <div class="row"> <div class="card card-body"> … -
nullable field default value django models in inhertiance
I have a model of product and another model called Course that inherits the product but has a video field and an author Which is a ForeignKey with A teacher model which inherits from the user model which inherits from AbstractUser Related Models: class User(AbstractUser): username = models.SlugField(default="", null=False, db_index=True, blank=True) # forced by django admin problems :( password = models.CharField(max_length=255, null=True) email = models.EmailField(max_length=255, unique=True) group = models.ManyToManyField(Group) is_teacher = models.BooleanField(default=False, null=False) is_seller = models.BooleanField(default=False, null=False) phoneNum = PhoneNumberField(null=False, unique=True, default='') USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username", "first_name", "last_name", "password"] def save(self, *args, **kwargs): self.username = slugify(self.first_name + self.last_name) super().save(*args, **kwargs) class Product(models.Model): name = models.CharField(max_length=100, null=False, blank=True) shoppers = models.ManyToManyField(User, related_name='shopper') tumb = models.ImageField(upload_to=course_tumb_directory_path, null=False) lastUpdate = models.DateTimeField(auto_now=True) price = models.DecimalField(null=False, default=1000000, max_digits=7, decimal_places=0) class Teacher(User): TOPICS = [ ("BP", "Basic Programming"), ("AP", "Advanced Programming"), ("CS", "Computer Science"), ("MS", "Mathematics"), ("CH", "Chemistry"), ("BL", "BioLogy"), ("PH", "physics"), ("EL", "Electronics"), ("RG", "Religious"), ("Or", "Other"), ] topic = models.CharField(max_length=2, choices=TOPICS, default=TOPICS[-1]) class Course(Product): video = models.FileField(upload_to=course_directory_path, null=True, validators=[ FileExtensionValidator(allowed_extensions=['MOV', 'avi', 'mp4', 'webm', 'mkv'])]) author = models.ForeignKey(Teacher, on_delete=models.CASCADE, null=True) when I'm trying to make migrations it says this: It is impossible to add a non-nullable field 'product_ptr' to course without specifying a … -
django testing fails with DoesNotExist even though it works when actually running
I'm trying to test if my PlayerPoint model can give me the top 5 players in regards to their points. This is the Player model: class Player(AbstractUser): phone_number = models.CharField( max_length=14, unique=True, help_text="Please ensure +251 is included" ) first_name = models.CharField( max_length=40, help_text="please ensure that you've spelt it correctly" ) father_name = models.CharField( max_length=40, help_text="please ensure that you've spelt it correctly" ) grandfather_name = models.CharField( max_length=40, help_text="please ensure that you've spelt it correctly" ) email = models.EmailField( unique=True, help_text="please ensure that the email is correct" ) age = models.CharField(max_length=3) profile_pic = models.ImageField(upload_to='profile_pix', default='profile_pix/placeholder.jpg') joined_ts = models.DateTimeField(auto_now_add=True, null=False) username = None and this is the PlayerPoint model: class PlayerPoint(models.Model): OPERATION_CHOICES = (('ADD', 'ADD'), ('SUB', 'SUBTRACT'), ('RMN', 'REMAIN')) points = models.IntegerField(null=False, default=0) operation = models.CharField( max_length=3, null=False, choices=OPERATION_CHOICES, default=OPERATION_CHOICES[2][0] ) operation_amount = models.IntegerField(null=False) operation_reason = models.CharField(null=False, max_length=1500) player = models.ForeignKey( settings.AUTH_USER_MODEL, null=False, on_delete=models.PROTECT, to_field="phone_number", related_name="player_points" ) points_ts = models.DateTimeField(auto_now_add=True, null=False) I also have a pre-save signal handler. @receiver(signals.pre_save, sender=PlayerPoint) if sender is PlayerPoint: try: current_point = PlayerPoint.objects.filter(player=instance.player).latest() except PlayerPoint.DoesNotExist as pdne: if "new player" in instance.operation_reason.lower(): print(f"{pdne} {instance.player} must be a new") instance.operation_amount = 100 instance.points = int(instance.points) + int(instance.operation_amount) else: raise pdne except Exception as e: print(f"{e} while trying to get … -
Ajax POST request is not working in Django project
I was trying to build a E Commerce website as part of my project. But the ajax "POST" using jquery is not working. I am not sure where it went wrong. Please forgive for my poor English.... {% extends "store/base.html" %} {% load static %} {% block title %} {{ product.name }} {% endblock %} {% block content %} <div class="container"> <main class="pt-5"> <div class="row g-3"> <div class="col-md-5 col-lg-5 order-md-first bg-light"> <img class="img-fluid mx-auto d-block" width="200px" alt="Responsive image" src="{{ product.image.url }}"> </div> <div class="col-md-7 col-lg-7 ps-md-3 ps-lg-5"> <h1 class="mb-0 h4">{{ product.title }}</h1> <p><span class="lead">{{ product.author }}</span> (Author)</p> <p>{{ product.description|slice:":355" }}...</p> <div class="border"> <div class="col border-bottom"> <div class="row p-3"> <div class="col-6">Hardback</div> <div class="col-6 text-end"><span class="h4 fw-bold">£{{ product.price }}</span></div> </div> </div> <div class="col"> <div class="row p-3"> <div class="col-6"> <label for="select">Qty</label> <select id="select"> <option value="">1</option> <option value="">2</option> <option value="">3</option> <option value="">4</option> </select> </div> <div class="col-6 text-end"> <button type="button" id="add-button" value="{{ product.id }}" class="btn btn-secondary btn-sm">Add to basket</button> </div> </div> </div> </div> </div> </div> </main> </div> <script> $(document).on('click', '#add-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "basket:basket_add" %}', data: { productid: $('#add-button').val(), csrfmiddlewaretoken: "{{csrf_token}}", action: 'post', }, success: function (json) { }, error: function (xhr, errmsg, err) {} }); }) </script> …