Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How could you show a bootstrap alert on mouseover of a choices field in a django form?
I have a questionnaire based on django form and I need to show a note if a user hovers or clicks on a question before it submits. The django form is loaded in from a custom question and question choices model. I had some luck with custom question formatting prior by handing django form label and choices a mark_safe str with html formatting of the title and options within. I took it a step further for this and attempted to put in some java script as well. Though it does not show anything on mouseover of the choice. In this case answer.content would be the individual choice underneath the question. Below is my mark_safe code which is only called when there is an explanatory_note for this answer choice, it is called right before handing it to django form typed choice field. I tried having it within the html page, but it would not work as it wouldn't be connected to an individual choice under a question. I have confirmed that the following str is correctly handed to the django form and used as a choice. It does correctly display answer.content. mark_safe("<p id=\"" + str(n) + "\">" + answer.content + "</p> … -
I've got many text i want to show on my page
I want it to be paginated. the data is from database.the data includes videos and images. so i want it to be like the text explaining while the images and videos demonstrate i did not have any idea on what code to write and i'm hoping someone outhere will help me -
Django and railway, ModuleNotFoundError: No module named 'mainApp.wsgi'
im new to this, so be nice xD 3 days working on it, i deployed my progect on railway from github, i just searched all the internet for a solution, but i cant. i can't figure out what the proble is this is my Procfile: web: gunicorn mainApp.wsgi --log-file - this is the path at my wsgi: Desktop\Project_countdown\mainApp\mainApp\wsgi.py" so i tryed: web: gunicorn mainApp/mainApp.wsgi --log-file - web: gunicorn mainApp/wsgi --log-file - web: gunicorn mainApp/mainApp/wsgi --log-file - web: gunicorn mainApp.wsgi:application --log-file - i can't get if the proble is here, or maybe in something in setting.py, even if railway should go by himself whit DATABASE_URL and stuff. my Procfile should be in the root, so should be ok: Desktop\Project_countdown\Procfile Thre requirements are ok. This is my setting.py from pathlib import Path import os import dj_database_url from dj_database_url import parse as dburl # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-j3fa@o20ztumez^!y9wq78)@nf&tr9a(21v7+u8(x*0!yfg0hp' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DEBUG', 'False') == 'True' ALLOWED_HOSTS = ['*'] #DATABASE_URL … -
Django Integrity Error: NOT NULL Constraint failed. How to fix?
I am new in django. I am weak of Relational Serialization. Please help me to solve the following problem. Problem: I want to create model, serializers and all the neccessary code. Basically I want to solve course sera project assesment of API course. When I run my code and test, I saw an error raised: django.db.utils.IntegrityError: NOT NULL constraint failed: LittleLemonAPI_menuitem.category_id It is occured when I define depth =1 in MenuItemSerializer and create a new menu item. If I remove depth = 1 and category = CategorySerializer; there is no error happend. But then category table data is not populated. Below I add my neccessary code: serializers.py from rest_framework import serializers, validators from .models import Category, MenuItem, Cart, Order, OrderItem from django.contrib.auth.models import User, Group, Permission class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ['id', 'slug', 'title'] validators = [ validators.UniqueTogetherValidator( queryset=Category.objects.all(), fields=('title',), message="Category must be unique" ) ] class MenuItemSerializer(serializers.ModelSerializer): class Meta: model = MenuItem category = CategorySerializer() fields = ['id', 'title', 'price', 'featured', 'inventory', 'category',] depth = 1 class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'groups',] depth = 1 class CartSerializer(serializers.ModelSerializer): class Meta: model = Cart user = UserSerializer() menuitem = MenuItemSerializer() … -
Is this JSON string valid and if so how to access nested items in Django view
I am trying to work through an issue where I am sending JSON from jQuery via Ajax(). In this function I create a nested array of objects, put the whole array through JSON.strigify() and then send it to my model in Django. I successfully decode the JSON string (No errors) but I can not access it or any of its parts. Same happens if I convert to dict() or list(). Is the JSON I am sending to my view valid for working with it in Django or do I need to change how I construct it in order to access its values. JQuery Constructing and sending array: $(document).on('click','#exModel',function () { const sending = []; $("table tr").each(function () { var p1 = $(this).find("th label").html(); var p2 = $(this).find("td input").attr('id'); var p3 = $(this).find("td input").val(); const build = {bnaa:p1,id:p2,vals:p3}; sending.push(build); }); console.log(sending); $.ajax({ url: '../coreqc/exModel/', data: JSON.stringify({'sending':sending}), type: 'POST', headers: {'content_type':'application/json','X-CSRFToken': '{{ csrf_token }}'}, async: 'true', success: function (data) { console.log("I made it back") //dom: 'Bfrtip', } }); }); The array is sent to my view in Django. In the browser console when I log it before send it looks like this: [{bnaa: "Product 1:", id: "1", vals: ""}, {bnaa: "Product 2:", … -
Building a CHAT WITH PDF Django Web App for College | Didn't getting accurate answers langchain
I am trying to build a Django, Langchain Pdf Chat Web App on which Students can upload their Syllabus PDF and Ask questions about it. similar to this Website. This is a College Project On AI & Web development. I have learned a lot about of it and Because of limited resources and being beginner. I have created a simple django web app on which can upload pdf and ask question from it and It uses, embedding, vectorstore, and Chat-gpt API and Providing the Answers but the Accuracy of Answers is very bad and sometimes completely irrelevant. Here is the code of the Project I create so far: From Views.py def upload_pdf(request): if request.method == 'POST': form = PDFUploadForm(request.POST, request.FILES) if form.is_valid(): pdf_doc = form.save() pdf_text = get_pdf_text([pdf_doc.pdf_file.path]) pdf_doc.processed_text = pdf_text pdf_doc.save() return redirect('process_pdf') else: form = PDFUploadForm() return render(request, 'pdf/upload_pdf.html', {'form': form}) def processing_text(request): pdf_docs = PDFDocument.objects.all() if not pdf_docs: return redirect('upload_pdf') raw_text = "".join([doc.processed_text for doc in pdf_docs if doc.processed_text is not None]) # If all processed_text are None, handle accordingly if not raw_text: print("All processed_text are None.") return redirect('upload_pdf') text_chunks = get_text_chunks(raw_text) vectorstore = get_vectorstore(text_chunks, api_key=OPENAI_API_KEY) vectorstore_id = str(len(vectorstore_dict)) vectorstore_dict[vectorstore_id] = vectorstore request.session['vectorstore_id'] = vectorstore_id return redirect('ask_question') … -
Render problem after updating an dictionary, Vue 3, Django, DRF
When i try to apply filters page's content doesn't update. First GET request is being sent after you move to localhost:8000/catalog/ I get another after setting the filters and sending a GET request to my API, and the respone is fine,but the DOM doesnt't update that's my getCatalogs method: getCatalogs(page = 1) { console.log("method getCatalogs called") const PAGE_LIMIT = 20 const tags = this.topTags.filter(tag => !!tag.selected).map(tag => tag.id) console.log("tags:", tags) const min = document.querySelector('input[name=minPrice]').value const max = document.querySelector('input[name=maxPrice]').value console.log("min:", min, "max:", max) if (parseFloat(min) !== 0) { this.filter.minPrice = parseFloat(min); } if (parseFloat(max) !== 50000) { this.filter.maxPrice = parseFloat(max); } this.updateUrlWithFilters() this.getData("/api/catalog/", { filter: { ...this.filter, minPrice: parseFloat(min), maxPrice: parseFloat(max) }, currentPage: page, category: this.category, sort: this.selectedSort ? this.selectedSort.id : null, sortType: this.selectedSort ? this.selectedSort.selected : null, tags, limit: PAGE_LIMIT }) .then(data => { console.log("response from API (data):", data); // create new list for correct displaying of changes this.catalogCards = [...data.results.items]; console.log("data.items:", data.results.items); console.log("catalogCards:", this.catalogCards); this.currentPage = data.currentPage; this.lastPage = data.lastPage; }).catch(error => { console.warn('couldnt get the catalog'); console.log(error); }) }, I have tried to use watch with force updating, but didn't work -
Django annotation for using left join
Models: class Operator_online(models.Model): name = models.TextField() role = models.TextField() class Reservations(models.Model): consultant_id = models.ForeignKey(Operator_online, on_delete=models.CASCADE) voip_number = models.IntegerField() Tried: consultants_operators = Operator_online.objects.filter( Q(role='consultant') | Q(role='support'), status='1' ) consultant_id_queryset = Reservations.objects.filter( consultant_id__in=consultants_operators ).select_related('consultant_id').annotate(role=F('consultant_id__role')).values( 'consultant_id', 'consultant_id__name', 'voip_number', 'role' ) Needs: Steel returning same above consultant_id_queryset queryset values: Returning all founded Operator_online (Which is role and name fields) plus existing appropriated Reservations (Which is consultant_id and voip_number) against what before returning only existed Reservations instances appropriated Operator_online. So for not founded Reservations instance which it's consultant_id field (foreignkey) has related to Operator_online returning null for voip_number and consultant_id -
Identity - Django View that accepts both Auth and Non-Auth users
I have integrated Azure AD with Django using identity[django] package (docs). It provides a @login_required decorator that is used to restrict a view only for AD authenticated users. The view function decorated should accept an additional parameter context which contains the AD info. I have written a custom decorator that creates a Django User object using the AD info provided by identity context. def custom_login_required(f): @wraps(f) @settings.AUTH.login_required def wrapped(request, context=None, *args, **kwargs): if context: request.user = get_ad_synced_user(context) return f(request, context=context, *args, **kwargs) return wrapped @custom_login_required def home(request, *, context): return render(request, 'home.html') <html> <body> {% if user.is_authenticated %} <p>Welcome, {{ user.username }}!</p> {% endif %} </body> </html> However, I want to create a view that accepts both authenticated and non-authenticated users. If the user is not authenticated, it should display a link to login page, and if the user is authenticated, then it should display private links. Using the Django User object, I can have access to request.user.is_authenticated, but since identity creates a separate object context (which gets AD info only when decorated with @login_required), I'm not sure how I can set request.user for the current request from the previous request. -
Unable to use Trigram search, despite it being installed
Hi I get issues with django being unable to run any trigram searches. I get errors such as django.db.utils.ProgrammingError: operator does not exist: unknown <<-> tsquery and django.db.utils.ProgrammingError: operator does not exist: character varying % tsquery and before you suggest it, the pg_trgm extension is installed! django=> SELECT * FROM pg_extension; oid | extname | extowner | extnamespace | extrelocatable | extversion | extconfig | extcondition -------+---------+----------+--------------+----------------+------------+-----------+-------------- 13659 | plpgsql | 10 | 11 | f | 1.0 | | 17002 | pg_trgm | 16388 | 2200 | t | 1.6 | | (2 rows) I installed it via a custom migration. Here is the block which is calling it: object_list = Quote.objects.annotate( distance=TrigramWordDistance('quote_text', query), ).filter(distance__lte=0.7).order_by('distance') If anyone can shed some light on why this may be happening I would appreciate it. -
How to set search paths for Heroku PostgreSQL database?
I'm currently deploying a Django app to Heroku, and my settings.py looks like this: if IS_HEROKU_APP: DATABASE_URL = dj_database_url.config( env="DATABASE_URL", conn_max_age=600, conn_health_checks=True, ssl_require=True, ) else: DATABASE_URL = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config('DATABASE_NAME'), 'USER': config('DATABASE_USER'), 'PASSWORD': config('DATABASE_PASSWORD'), 'HOST': config('DATABASE_HOST'), 'PORT': config('DATABASE_PORT'), } DATABASES = { 'default': { **DATABASE_URL, 'OPTIONS': { 'options': '-c search_path=public' }, }, 'modules': { **DATABASE_URL, 'OPTIONS': { 'options': '-c search_path=modules' }, }, 'alumni': { **DATABASE_URL, 'OPTIONS': { 'options': '-c search_path=alumni' }, } } DATABASE_ROUTERS = ['MCMT.db_routers.ModulesRouter', 'MCMT.db_routers.AlumniRouter', 'MCMT.db_routers.DefaultRouter'] This works locally but not when I push to Heroku (specifically in the release phase, when I have to migrate). I get the error: django.db.utils.ProgrammingError: relation "info" does not exist remote: LINE 1: SELECT "info"."code" FROM "info" which is because there is no table "info", only "modules.info". I think this is because Heroku failed to see the search_path options. How should I resolve this? I have tried to create the schemas first using heroku pg:psql, but that gives me the same error. I also tried to see if it's an issue with dj_database_url but I fail to find any solution online. -
Code highlighting with Markdown, Pygments and CodeHiliteExtension in Django. Regular code blocks work nice, but inline code like `print("hi")` doesn't
I have a problem with Markdown, Pygments and CodeHiliteExtension in Django. I have a blog post written in Markdown, then I have a save function like that: def save(self, *args, **kwargs): # Convert Markdown to HTML with syntax highlighting self.text_html = markdown.markdown( str(self.text_markdown), extensions=[ "extra", "fenced_code", CodeHiliteExtension(linenums=False, css_class="codehilite", pygments_style="lightbulb"), ], ) self.preview_html = markdown.markdown( str(self.preview_markdown), extensions=[ "extra", "fenced_code", CodeHiliteExtension(linenums=False, css_class="codehilite", pygments_style="lightbulb"), ], ) super().save(*args, **kwargs) It works nicely - I mean it's highlighting a full Mardown code blocks with all syntax like that: /```python /print("hi") /``` (without the forward slash, I used it as an escape character for the post formatting). But the inline code like that - ``print("hi")` is not working. I tried to use variations of pymdownx.inlinehilite in extensions but I wasn't able to make it work. After some googling I found this - https://facelessuser.github.io/pymdown-extensions/extensions/inlinehilite/ And right now I am able to get inline code to highlight properly by using regex and manually adding missing characters like - ":::language mycode" but it's of course far from the clean solution. I was also looking into prism.js (which works well) but I wanted to avoid using additional JavaScript. But maybe it will be cleaner after all? So I wanted to … -
Cannot run my django project with apache (caught sigwinch, shutting down gracefully)
I am new to web development, I am trying to build a backend website with python django. I followed the tutorial on w3schools and built a django project, and now trying to deploy an apache server on aws ec2 server. Every time i start the apache server, it shutdown gracefully (IDK why) and cannot connect to the django page (venv) ubuntu@ip-:~/ $ sudo systemctl start apache2 (venv) ubuntu@ip-:~/ $ sudo tail -f /var/log/apache2/error.log [Sat Oct 26 13:03:39.971797 2024] [core:notice] [pid 111983:tid 135507726227328] AH00094: Command line: '/usr/sbin/apache2' [Sat Oct 26 13:23:09.371710 2024] [mpm_event:notice] [pid 111983:tid 135507726227328] AH00492: caught SIGWINCH, shutting down gracefully [Sat Oct 26 13:23:20.282166 2024] [mpm_event:notice] [pid 112434:tid 124451557558144] AH00489: Apache/2.4.58 (Ubuntu) mod_wsgi/5.0.0 Python/3.12 configured -- resuming normal operations [Sat Oct 26 13:23:20.284200 2024] [core:notice] [pid 112434:tid 124451557558144] AH00094: Command line: '/usr/sbin/apache2' [Sat Oct 26 13:27:10.328301 2024] [mpm_event:notice] [pid 112434:tid 124451557558144] AH00492: caught SIGWINCH, shutting down gracefully [Sat Oct 26 13:27:10.443212 2024] [mpm_event:notice] [pid 112577:tid 124457667811200] AH00489: Apache/2.4.58 (Ubuntu) mod_wsgi/5.0.0 Python/3.12 configured -- resuming normal operations [Sat Oct 26 13:27:10.444580 2024] [core:notice] [pid 112577:tid 124457667811200] AH00094: Command line: '/usr/sbin/apache2' [Sat Oct 26 13:27:19.027280 2024] [mpm_event:notice] [pid 112577:tid 124457667811200] AH00492: caught SIGWINCH, shutting down gracefully [Sat Oct 26 13:27:33.935103 2024] … -
Why does Django generate extra queries for related fields?
I am using drf and django-debug-toolbar. # model class Item(models.Model): title = models.CharField(max_length=255) description = models.TextField() owner = models.ForeignKey(User, on_delete=models.CASCADE) # serializer class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ["id", "title", "description", "owner"] view class ItemViewSet(ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer And I noticed this extra query that gets generated and I don't know why. SELECT "marketplace_user"."id", "marketplace_user"."password", "marketplace_user"."last_login", "marketplace_user"."is_superuser", "marketplace_user"."first_name", "marketplace_user"."last_name", "marketplace_user"."is_staff", "marketplace_user"."is_active", "marketplace_user"."date_joined", "marketplace_user"."email" FROM "marketplace_user" LIMIT 1000 Can someone help me to figure this out? -
Django Chatroom model: Retrieve latest messages from all rooms a user is part of
I'm having a hard time constructing a query (sqlite) to get the latest message for each chatroom a user is part of. This is my model in Django: class Membership(models.Model): room_name = models.TextField() members = models.ManyToManyField(CustomUser, through="Message") class Message(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) room = models.ForeignKey(Membership, on_delete=models.CASCADE) advertisement = models.ForeignKey(Advertisement, on_delete=models.CASCADE, default=None) message = models.TextField() created_at = models.DateTimeField(auto_now_add=True) class CustomUser(AbstractUser): username = models.CharField(max_length=200, unique=False) Now with this in mind I would like to display all rooms a user is part of and additionally the latest message in a room. I feel like I'm close: select * from chat_message as cm inner join (select max(id) as lm from chat_message group by room_id) as last_messages on last_messages.lm = cm.id inner join main_advertisement ma on cm.advertisement_id = ma.id inner join chat_membership as cmb ON cm.room_id = cmb.id order by id; Which looks like this gives me the latest messages (and other data) for each room but now I struggle to filter for just 1 user (e.g. user_id = 3). Any ideas would be appreciated, also for possible hints how to start constructing this in the django ORM. -
How to add a default image to django ImageField with Amazon S3 for file storage?
I made a custom user model that contains an imagefield for the avatar: class User(AbstractUser): avi_pic = models.ImageField( upload_to='avi/', default='avi/default_avi.jpg') username = models.CharField(max_length=30, unique=True) bio = models.CharField(max_length=150, null=True, blank=True, default='') def __str__(self): return self.username I want to have a default avi for all new users so I added the image to my AWS3 bucket and added the path to the model field. The path to that image in my S3 bucket is: mybucket/media/avi/default_avi.png To create the user i have an APIView: class CreateUser(APIView): def post(self, request): serializer = UserRegisterSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ^ when registering new user only a username is submitted. and model serializer: class UserRegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username') def validate_username(self, value): if User.objects.filter(username=value).exists(): raise serializers.ValidationError("Username is already taken.") allowed_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.' if any(char not in allowed_characters for char in value): raise serializers.ValidationError( "Invalid characters in username.") return value My problem is that when i create a new account the user doesn't get the default image. I have configured my settings like this: AUTH_USER_MODEL = 'users.User' STATIC_URL = 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = 'https://MYBUCKET.s3.amazonaws.com/media' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME … -
how to filter datetime by day in django with timezone utc aware?
the datetime objects im trying to filter are 2024-10-26 00:49:34.131805 in the database, which is 9pm in my country. what happens is that when im trying to filter by day (created_at__day=timezone.now().day) it returns day 26, which is ok, but django translates them to the correct timezone (9pm the previous day) when filtering and ends up mismatching values what i need to do? settings.py TIME_ZONE = 'America/Sao_Paulo' USE_I18N = True USE_TZ = True models.py created_at = models.DateTimeField(auto_now_add=True) query day = timezone.now().day filter = Model.objects.filter(created_at__day=day) this is what i tried date = timezone.now() filter = Model.objects.filter(created_at__date=date) and that worked... but i really wanted to filter just by day. does django provide something or am i doing something wrong? -
Why the email is not sending into my other email with that created object?
My idea is when someone submits the form and object created and my email verified in the settings with my app password sends an email to my other work email. My scenario is: Scenario: Omar Haji has a personal website with a "Contact Me" form. A visitor, named Sarah, visits the website and wants to get in touch. She fills out the form with the following information: Name: Sarah Alami Email: sarah@example.com Subject: Inquiry about Collaboration Message: "Hi Omar, I came across your portfolio, and I am interested in collaborating on a web development project. Let’s connect!" When Sarah clicks the "Send Message" button, the following happens behind the scenes: What Happens Step by Step: Form Submission: Sarah's information (name, email, subject, and message) is sent to the contact view in your Django project. Saving the Submission: The contact view creates a new instance of the ContactSubmission model using the data provided by Sarah. This instance is saved in the database with the information she submitted. Sending the Email: Immediately after saving the form data, the view uses Django's send_mail function to send an email from the email in the settings into this email myworkemail@gmail.com with sarah object Here's my … -
Unable to get multiple value in a django model
I am trying to get multiple values for a single label and that label will get two input values. I have added it successfully in the Django admin but when I send a request it gives me a string instead of an array. I have tried the code below. I hope that helps to get the solution. model.py class Product(models.Model): secondary_author = models.JSONField(blank=True, null=True) My admin.py class TwoValuesWidget(forms.MultiWidget): def __init__(self, attrs=None): widgets = [ forms.TextInput(attrs={'placeholder': 'Value 1'}), forms.TextInput(attrs={'placeholder': 'Value 2'}) ] super().__init__(widgets, attrs) def decompress(self, value): # Ensure the value is properly decompressed if isinstance(value, list) and len(value) == 2: return value # If valid list with two values, return it elif isinstance(value, str) and value.startswith('[') and value.endswith(']'): # If value is a stringified list, convert to list import ast return ast.literal_eval(value) return ['', ''] # Default to two empty fields if no valid value class MyModelForm(forms.ModelForm): secondary_author = forms.CharField(widget=TwoValuesWidget(), label="Secondary Author") class Meta: model = Product fields = '__all__' def clean_secondary_author(self): values = self.cleaned_data['secondary_author'] print(values) return values class ProductAdmin(admin.ModelAdmin): form = MyModelForm def save_model(self, request, obj, form, change): obj.secondary_author = form.cleaned_data.get('secondary_author', []) super().save_model(request, obj, form, change) admin.site.register(Product,ProductAdmin) ``` -
Trouble Understanding how to create Custom User Model in Django
Here’s a brief overview of what I’ve accomplished so far, to ensure we're all on the same page. Please note that I’m still new to Django, so my approach might not be perfect or even close to what it should be. Created a new Django project and applied the initial migrations right away (18 or 19) Next thing I did is create a new app called "authorization", so like this python3 manage.py startapp authorization And then I added it to the "INSTALLED_APPS" list in my projects settings.py file I then created the following in the models.py file from django.db import models from django.core.validators import MinValueValidator from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class CustomUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError('Please provide a value for email!') email = self.normalize_email(email) user = self.model(email = email, **extra_fields) user.set_password(password) user.save(using = self.db) return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('role', 'OWNER') extra_fields.setdefault('subscribed', True) return self.create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): # id provided by default username = models.CharField( max_length = 30, unique = True ) email = models.EmailField(unique = True) # password provided by default favoriteFood = models.CharField(max_length = 255) favoriteSnack = models.CharField(max_length = 255) favoriteDrink = … -
Django Static Files Not Uploaded Properly to Digitalocean Spaces using S3
I am working on a django project v5.1 and as always I use digitalocean spaces for my static and media files. Here is the default configuration I always use: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Our apps ..., ..., ..., ..., # Third party apps 'storages', ] # DigitalOcean Spaces Configuration AWS_ACCESS_KEY_ID = os.getenv('DO_SPACE_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('DO_SPACE_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('DO_SPACE_BUCKET_NAME') AWS_S3_ENDPOINT_URL = f"https://{os.getenv('DO_SPACE_BUCKET_NAME')}.{os.getenv('DO_SPACE_REGION')}.digitaloceanspaces.com" AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', # Cache static files for 1 day } # Static and Media Files Settings STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # Static and Media URL STATIC_URL = f"{AWS_S3_ENDPOINT_URL}/static/" MEDIA_URL = f"{AWS_S3_ENDPOINT_URL}/media/" STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # Optional configurations to prevent overwrite of files with the same name AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None But this time I am running into problems. Usually I do not define STATIC_ROOT as I am using Boto3, but now it is giving me this error if I do not define it when I run collectstatic: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. But when I do include it, it collects static files in the staticfiles folder I defined, instead of uploading to digitalocean spaces. … -
How to create an abstract GraphQL mutation in Wagtail (Django) with Graphene
I'm trying to make a mutation to create a page in Wagtail using graphene-django. The type of the created page should depend on passed parameters. All of the pages that are supposed to be created use the same input, which is: class PageInput(InputObjectType): parent_id = Int(required=True) page_id = Int(required=True) page_name = String(required=True) , where page_id is the id from the other app and page_name is the record name from the other app - both passed to Mutation as parameters. Since all pages have the same input, they are supposed to have common mutate() method. What is different for each type is the type-specific prepare_pages() method. What I want to achieve is to have an abstract CreatePage mutation class, which will define the mutate() method and several classes that inherit this one and implement their own prepare_pages() method. I implemented the abstract class this way: class CreatePages(Mutation): class Meta: abstract = True class Arguments: pages = List(PageInput) page_ids = List(Int) creation_times = List(String) def prepare_pages(pages): raise NotImplementedError("Subclasses must implement this method.") @classmethod def mutate(cls, root, info, pages): page_ids = [] creation_times = [] pages_to_create = cls.prepare_pages(pages) for page in pages_to_create: try: page.save_revision().publish() page_ids.append(page.page_id) creation_times.append(page.latest_revision_created_at .strftime('%Y-%m-%d %H:%M:%S')) except Exception: continue return cls(page_ids=page_ids, … -
Django: implement several different id numerations for foreign keys
I have a forum app, its structure is "forum -> subforum -> topic -> comments". Topics are special for each subforum and are not availiable from another subforum; the same for topics and their comments. Due to bad organization of the data structure from my side, comments' id numeration iterates as common for all of the topics, so id of the first comment of the first created topic is 1, while id of the first comment of the last created topic might be, I don't know, 45. I need to address comments inside topics via their id (or some other type of numeration), and for that sake some obvious numeration of comments system inside the topics is required. Though I don't know how to implement it and is it possible at all. Thus I'm asking for the help of community. Files: forum/urls.py: from django.urls import path from forum.views import * app_name = 'forum' urlpatterns = [ path('', SubForumListView.as_view(), name='forum'), path('<slug:subforum_slug>/', TopicListView.as_view(), name='subforum'), path('<slug:subforum_slug>/add_topic/', AddTopic.as_view(), name="add_topic"), path('<slug:subforum_slug>/topics/<slug:topic_slug>/', ShowTopic.as_view(), name='topic'), path('<slug:subforum_slug>/topics/<slug:topic_slug>/add_comment/', AddComment.as_view(), name="add_comment"), path('<slug:subforum_slug>/topics/<slug:topic_slug>/edit/<int:id>/', UpdateComment.as_view(), name="edit_comment"), ] models.py: from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils.text import slugify from .consts import * class Subforum(models.Model): title = … -
how to Sort values of a qury in Django based on the quantity of child table?
Hello guys i have a Product Class that have a child class ProductColors this is my two class : class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField(unique=True, allow_unicode=True) description = models.TextField() price = models.PositiveIntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) discount = models.PositiveIntegerField(default=0) offer_end = models.DateTimeField(blank=True, null=True) user_likes = models.ManyToManyField(User, related_name="product_likes", blank=True) and : class ProductColor(models.Model): class ColorChoices(models.TextChoices): RED = "#f50b0b","قرمز" BLUE = "#0844f3","آبی" YELLOW ="#f7f704", "زرد" GREEN = "#22f704","سبز" PINK = "#f704e8","صورتی" PURPLE = "#901f89","بنفش" GRAY = "#9c939c","خاکستری" WHITE = "#ffffff","سفید" BLACK = "#000000","سیاه" ORANGE = "#f2780c","نارنجی" BROWN = "#513924","قهوه ای" GLASS = "#f3f3f2", "بی رنگ" product = models.ForeignKey(Product, related_name='colors', on_delete=models.CASCADE) color = models.CharField(choices=ColorChoices.choices, max_length=255) quantity = models.PositiveIntegerField(default=0) def __str__(self): return f"{self.product.name} - {self.color}" i am trying to sort products based on first -available and then the quantity of colors from higher quantity to zero i try to do this with this method : from django.db.models import Count, When, Case, IntegerField products = Product.objects.all().order_by('-available', 'name') products = products.annotate( has_zero_quantity=Case( When(colors__quantity=0, then=1), When(colors__quantity__gt=0, then=0), output_field=IntegerField(), ) ) but i stuck and i cant find the correct way anyone can help for solution ? -
Django admin pannel redirect to /accounts/login/?next=/admin/
Whenever I open my django admin pannel it redirects to the following URL /accounts/login/?next=/admin/ I'm using DRF and all my DRF APIs running properly but my admin pannel is not opening every time it is redirecting to above URL. But I didn't setup any above URL in my project setup.