Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integrating DBT Semantic Layer to LLM
I’m working on a Django application where I want to enable natural language querying capabilities using an OpenAI language model (LLM) like GPT-3. To structure and simplify the database access, I plan to use a DBT (Data Build Tool) semantic layer. My goal is to allow users to ask questions in natural language, which are then translated into SQL queries through the LLM, utilizing the semantic definitions provided by DBT. This setup should ideally support complex queries across multiple tables, leveraging the relationships and dimensions defined in the semantic layer. Here’s a brief outline of the setup: 1. Django Application: Serves the frontend and backend, managing user requests. 2. DBT Semantic Layer: Defines the data models, metrics, and relationships. 3. OpenAI LLM (e.g., GPT-3): Used for interpreting natural language inputs and generating SQL queries. 4. PostgreSQL Database: The source of data queried and managed via DBT. Specific Questions: 1. How should I integrate the DBT semantic layer within the Django app? Should the semantic layer be exposed via an API, or is there a more integrated approach? 2. What are the best practices for using an LLM to generate SQL queries from natural language, especially using the constructs defined in … -
I have some problem in the get number of whishlist and show this?
In the following this error... I have problems getting the number of likes for products and removing likes from the list of favorites. like correctly in the database (add to favorite) but I don't know how to get their number and make it dynamic in JavaScript codes by Ajax. Can you look at my codes and give me the necessary guidance, what should I add or remove? thank you! favorite.py from apps.comment_scoring_favorites.models import Favorite class favoriteProduct: def __init__(self,request) -> None: self.session=request.session favorite_product=self.session.get('favorite_product') if not favorite_product: favorite_product=self.session['favorite_product']=[] self.favorite_product=favorite_product self.count=Favorite.count_favorites_by_session() def __iter__(self): favorite_product=self.favorite_product.copy() for item in favorite_product: yield item def add_to_favorite_product(self,productId): productId=int(productId) if productId not in self.favorite_product: self.favorite_product.append(productId) self.count=Favorite.count_favorites_by_session() self.session.modified=True def delete_from_favorite_product(self, productId): productId=int(productId) self.favorite_product.remove(productId) self.count=Favorite.count_favorites_by_session() self.session.modified=True middleware.py import threading class RequestMiddleware: def __init__(self,get_response,thread_local=threading.local()): self.get_response=get_response self.thread_local=thread_local def __call__(self,request): self.thread_local.current_request=request response=self.get_response(request) return response models.py from middlewares.middleware import RequestMiddleware class Favorite(models.Model): product=models.ForeignKey(Product,on_delete=models.CASCADE,related_name='favorite_product',verbose_name='کالا') favorite_user=models.ForeignKey(CustomUser, on_delete=models.CASCADE,related_name='favorite_user1',verbose_name='کاربر علاقه مند') register_date=models.DateTimeField(auto_now_add=True,verbose_name='تاریخ درج') def __str__(self) -> str: return f"{self.product} - {self.favorite_user}" class Meta: verbose_name='علاقه' verbose_name_plural='علایق' def count_favorites_by_session(self): request=RequestMiddleware(get_response=None) request=request.thread_local.current_reques session=request.session favorite_product_ids =session.get('favorite_product') return self.objects.filter(product__id__in=favorite_product_ids).count() views.py class ShowFavoriteListView(View): def get(self,request,*args,**kwargs): favorite_list=favoriteProduct(request) context={ 'favorite_list':favorite_list, } return render(request,'csf_app/partials/create_favorites.html',context) def statuse_of_favorite_list(request): favoriteList=favoriteProduct(request) return HttpResponse(favoriteList.count) def add_to_favorite(request): productId=request.GET.get('productId') product=Product.objects.get(id=productId) flag=Favorite.objects.filter( Q(favorite_user_id=request.user.id) & Q(product_id=productId)).exists() if(not flag): Favorite.objects.create( product=product, favorite_user=request.user, ) return HttpResponse('added to favorite lists') … -
Migrate a standalone SQLite 3.12.x database with Django configuration
I'm evaluating the use of django for the migration of a SQLite database to Postgres. The database was not created as a django project, but instead used for other applications. I'm attempting to configure django to do routine migrations of various development SQLite databases to Postgres. I continue to fail with regard django creating the json exports from SQLite. I receive the following error: CommandError: Unable to serialize database: no such table: django_admin_log I have configured my database in settings.py I have run python manage.py inspectdb > models.py for migration tips etc.. Perhaps I'm missing the preconfiguration steps etc...and looking for help. -
Unable to update user profile using PUT method (Django DRF)
I am currently working on a mentor-mentee matching service using Django DRF. I have made a 'users' app and have completed creating users&logging in. But I can't edit user info using PUT method. Here are my project files (models.py, serializers.py, views.py, urls.py, settings.py) 1. models.py # users/models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.core.exceptions import ValidationError from django.core.validators import MaxValueValidator, MinValueValidator class User(AbstractUser): is_mentor = models.BooleanField(default=False) profile_pic = models.ImageField(upload_to='profile_pics/', default = 'default.png') # profile_pic dir 만들기, default이미지 업로드하기, 사진 첨부 루트 만들기 name = models.CharField(max_length=50, verbose_name= ("이름")) birth_date = models.DateField(verbose_name= ("생년월일"), null=True, blank=True) agreed_to_terms = models.BooleanField(default=False, verbose_name= ("이용약관 동의")) @property def role(self): return "Mentor" if self.is_mentor else "Mentee" class Interest(models.Model): INTEREST_CHOICES = ( ('belief', '가치관'), ('finance', '재테크'), ('love', '사랑'), ('daily', '생활 지식'), ('relationship', '인간 관계'), ('career', '진로'), ) name = models.CharField(max_length=20, choices=INTEREST_CHOICES, unique=True) def __str__(self): return self.get_name_display() class Mentor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='mentor') interests = models.ManyToManyField(Interest, through='MentorInterest') rating = models.FloatField(default=0, validators=[MinValueValidator(0), MaxValueValidator(5)]) total_ratings = models.PositiveIntegerField(default=0) def clean(self): super().clean() if self.interests.count() > 3: raise ValidationError("mentors can choose under 3 interest.") def update_rating(self, new_rating): self.rating = ((self.rating * self.total_ratings) + new_rating) / (self.total_ratings + 1) self.total_ratings += 1 self.save() class MentorInterest(models.Model): mentor = models.ForeignKey(Mentor, on_delete=models.CASCADE) interest = models.ForeignKey(Interest, … -
Django date input format seems not to be accepted
I put a DateField inside a ModelForm, which seems to work fine, if I add new entries to my database. Then I added a page, where I can edit one of those entries. Of course, I am passing the date of the desired entry to the HTML, but the date format is not set as expected. # models.py class SomeModel(models.Model): someDate = models.DateField() description = models.CharField(max_length=100) # forms.py class SomeForm(forms.ModelForm): someDate = forms.DateField(input_formats=["%d.%m.%y"], label="Some Date") class Meta: model = SomeModel widgets = { "someDate": forms.DateInput(format=("%d.%m.%y")) } # views.py def someModel_edit(request: HttpRequest, id: int): # ... query = SomeModel.objects.get(id=id) form = SomeForm(instance=query) args = { 'form': form } return render(request, 'SomeHtml.html', args) {% extends 'base.html' %} {% block content %} <h2>Edit Model</h2> <form action="{% url 'someModel_edit' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" name="edit-someModel" value="Edit"> </form> {% endblock %} I expect the format of the date in the edit page to be as I configured in the forms.py file (e.g. 12.08.2024). Sadly it always looks like this: And even worse, if I edit the description of the model entry and hit save, the software tells me, that I use the wrong date format. -
How to automatically create a user in django
I'm trying to create an application form so that people who would like to work for us can apply to our organization. I had a conversation with my client and he doesn't want new employees to create their own user login info. Instead, he wants me to create an admin page where he'll accept or decline applicants. If he accepts an applicant, it'll automatically create user login info, and email that applicant their login info. The user will of course be able to change their login info once they enter their account. How can this be done? I tried to create a signup sheet, but that ended up creating a user before the admin accepted the applicant. User = get_user_model() class InterpreterCreationForm(UserCreationForm): address = forms.CharField(widget=forms.Textarea) phone_number = forms.CharField(max_length=15) ssn = forms.CharField(max_length=15, required=False) languages = forms.ModelMultipleChoiceField(queryset=Language.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def save(self, commit=True): user = super().save(commit=False) user.is_interpreter = True if commit: user.save() interpreter = Interpreter( user=user, address=self.cleaned_data['address'], phone_number=self.cleaned_data['phone_number'], ) interpreter.save() interpreter.languages.set(self.cleaned_data['languages']) return user -
How to connect to PostgreSQL DB on PythonAnywhere?
I uploaded a site that is the basic Django "Hello World" site with a few changes. For one thing, the DB is configured to use Postgres. This works fine locally but I am having trouble understanding how to complete the setup on PythonAnywhere. On PA the DB was set up using psql as follows: CREATE DATABASE domain_db; CREATE USER domain_admin WITH PASSWORD '123456789'; \connect domain_db; CREATE SCHEMA domain_schema AUTHORIZATION domain_admin; -- Settings recommended by Django documentation ALTER ROLE domain_admin SET client_encoding TO 'utf8'; ALTER ROLE domain_admin SET default_transaction_isolation TO 'read committed'; ALTER ROLE domain_admin SET timezone TO 'UTC'; Note that this approach is based on recommendations due to changes to Postgres permissions changes with v15 (which is what we are using locally). I am assuming that this works with v12, which is what I think PA is using. Could be wrong on that. https://gist.github.com/axelbdt/74898d80ceee51b69a16b575345e8457 https://www.cybertec-postgresql.com/en/error-permission-denied-schema-public/ The project directory structure looks like this: domain/ site/ _config/ settings/ base.py Settings common to local and production local.py Local development settings production.py Production server settings asgi.py urls.py wsgi.py staticfiles/ manage.py venv .env In base.py I configure the database using environment variables loaded from the .env file. I have confirmed that the .env file is … -
Running a django app on an apache server with Xampp
I am a junior dev and have landed my first role but have no one here to ask questions to. I have been tasked with migrating our company app from the current server to a new server. I have been doing some research and looking through our code to orient myself with their system design. They are currently running their app directly from their server. I know nothing about server config. From my research i found the mod_wsgi is used and have found the httpd.conf file and saw that it is point to the project folder on the C:/. Can anyone walk me through the process of setting up a new server and what files i need to configure? Currently they have it setup on an apache server which is controlled by xampp (all new to me). I haven't toyed around with things too much because i changed branches the other day and their entire program companywide stopped working. So i dont want to start breaking things until i am sure i can recover it. -
KQL Query Formatting/Prettify Library
I am running a Django web app and would like to show some KQL query to the user. However, the query is in a single line, and I would like to format/prettify it. How can it be done? Do I really have to run a separate server running Node.js that than can prettify the code? Can I use the js files in @kusto/monaco-kusto or @kusto/language-service-next to prettify and syntax highlight the KQL queries on my web app? -
Can't load page..... page not found error?
When I load the pages in my project Django keeps showing me a page not found error. I have already written the views and their corresponding urls in the views.py and urls.py files and it is still saying that the page is not found when I load it. My index file is not affected by this error, but when I want to access other files the error popes up I ran manage.py runserver to load the index page but when I want to access the other pages through the nav-bar the error pops up -
Why is my API retrieving data from the database faster than from Redis?
I'm working with Django and GraphQL to create a backend for an e-commerce application. Initially, the API for retrieving products was slow, so I decided to implement a Redis stack to speed it up. However, I found that retrieving data from Redis is much slower than retrieving it from the database. Below are the details of my implementation: Database Query: def resolve_products(self, info, **kwargs): (filter_objects, method_filter, seller_lst, name, ar_name) = ( product_obj.call_filter_product() ) kwargs["seller_list"] = eller_lst query = ( Products.objects.filter(filter_objects, method_filter, active=True) .filter(variants__seller__id__in=list(seller_lst)) .distinct() ) query = query.filter( Exists( Variant.objects.filter( product_id=OuterRef("id"), seller_id__in=seller_lst, stock_available=True, ) ) ) start_index = int(offset) end_index = start_index + int(kwargs.get("first")) query_set = query[start_index:end_index] final_qs = query_set.annotate( stock_available=Exists( Variant.objects.filter( product_id=OuterRef("id"), seller_id__in=seller_lst, stock_available=True, ) ) ) # Determine hasNextPage has_next_page = end_index < len(query) connection = ProductsConnection( edges=[ProductsConnection.Edge(node=product) for product in final_qs], total_count=query.count(), details={ "header_en": name, "header_ar": ar_name, "method": kwargs.get("method"), }, ) connection.page_info = PageInfo( start_cursor=start_index, end_cursor=( int(kwargs.get("first")) + 1 if int(offset) == 0 else int(offset) + int(kwargs.get("first")) ), has_next_page=has_next_page, has_previous_page=start_index > 0, ) return connection Redis Implementation: seller_lst = obj.get_seller_lst() redis_obj = RedisUtility() data = redis_obj.get_products(seller_lst, **kwargs) if data: product_ids = [int(product['id']) for product in data['products']] products = Products.objects.filter(id__in=product_ids) connection = ProductsConnection( edges=[ProductsConnection.Edge(node=product) for product in products], … -
Transparent png in Django navigation bar not working
I am currently building a website with Django. Then I tried to add a logo to the navigation bar by inserting a png file with transparent background, but strangely the background remained white. So I combined part of base.html and part of navbar.html to create a file called test.html, and here the image is also displayed fine with transparent background. I hope you can help me to solve this problem. I am currently using Django 4.0.3. logo file is IMG_1706.png style.css is empty. logo file test.html My django server [code] test.html (just html) <!-- navigation bar --> <!doctype html> <html lang="ko"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" type="text/css" href="../static/bootstrap.min.css"> <!-- cubestudio CSS --> <link rel="stylesheet" type="text/css" href="../static/style"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light border-bottom"> <div class="container-fluid"> <a class="navbar-brand"><img src="../static/IMG_1706.png" class="img-fluid" alt="CubeStudio" width="200" height="150"></a> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-rg-0"> </ul> </div> </div> </nav> </body> </html> base.html (django) {% load static %} <!doctype html> <html lang="ko"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" type="text/css" href="{% static 'bootstrap.min.css' %}"> <!-- my CSS --> … -
SMTPAuthenticationError at /appointment/ (535, b'5.7.3 Authentication unsuccessful [BLAPR03CA0003.namprd03.prod.outlook.com 08DCAE8BF31BEC3D]')
My code works absolutely fine on local server, but I deployed it using a custom domain from godaddy and now everything's wrong with it. I am using outlook mail. I don't know how to fix this. Other fixes I've seen only work for organization email and I have a personal email. I don't have the paid office365 version, I don't know if I need it just to send mail. My settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST = 'smtp-mail.outlook.com' EMAIL_HOST_USER = "email@outlook.com" EMAIL_HOST_PASSWORD = "pass" DEFAULT_FROM_EMAIL = "email@outlook.com" -
How to setup sentry for django celery-beat?
I've setup sentry in my demo python project in settings.py. sentry_sdk.init( dsn=os.getenv('SENTRY_KEY'), # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. traces_sample_rate=1.0, # Set profiles_sample_rate to 1.0 to profile 100% # of sampled transactions. # We recommend adjusting this value in production. # profiles_sample_rate=1.0, ) Now I want to enable it for the celery-beat. What is the way to integrate it or update the existing config in settings.py? The Sentry doc says: Initialize Sentry in the celeryd_init or beat_init signal Does it require to create a celery task.py?How to automatically start this task when running python manage.py runserver or celery? -
Maybe a bad implementation of Django signals
I recently deployed a full stack project using Django, Gunicorn and Nginx. Briefly speaking, it is a website for a friend of mine, a space in which he can share and publish his recent activities (such as published albums, photoshoots and articles). I tried to automatize the information collections for populating a model instance by uploading a file (for a faster, cleaner and easier upload from the admin panel) using several Django signals. My idea was: if I upload from the admin panel a perfectly formatted file (.docx), using signals and other functions I will be able to fill the information and that's it. But, if I delete an instance (ie an Album or an Article), I'd like that this would have effects on files (I mean, delete files from the media folder on the server). Before posting my code, I'd like to tell that in developing this approach works perfectly and it's the same for different models. Sadly, it does not in production. More precisely, the file upload works perfectly, the processing sometimes doesn't (and I'm left with empty fields), the file deletion for some models works, for other does not at all. settings.py INSTALLED_APPS = [ 'musicsite.apps.MusicsiteConfig', ... … -
Custom Email Validation in Djoser Registration Not Working
I'm using Django with Djoser for authentication and need to restrict user registration to only those emails listed in my kontakte table. However, my custom email validation doesn't seem to be invoked. Here are the details: Djoser Configuration: DJOSER = { "PASSWORD_RESET_CONFIRM_URL": "auth/password-reset-confirm?uid={uid}&token={token}", "ACTIVATION_URL": "auth/activation?uid={uid}&token={token}", "SEND_ACTIVATION_EMAIL": True, "USER_CREATE_PASSWORD_RETYPE": True, "PASSWORD_RESET_CONFIRM_RETYPE": True, "PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND": True, "TOKEN_MODEL": None, "FROM_EMAIL": getenv("FROM_EMAIL"), "SERIALIZERS": { "user_create": "users.serializers.CustomUserCreateSerializer", }, } Custom Serializer: from rest_framework import serializers from djoser.serializers import UserCreateSerializer from .models import UserAccount, Kontakte class CustomUserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = UserAccount fields = ("email", "password", "is_active", "is_staff", "is_superuser") def validate_email(self, value): if not Kontakte.objects.filter(email=value).exists(): raise serializers.ValidationError("You are not allowed to register.") return value def create(self, validated_data): user = UserAccount.objects.create_user( email=validated_data["email"], password=validated_data["password"] ) return user Problem: The custom email validation in CustomUserCreateSerializer doesn't seem to be invoked during registration. I need the registration to check the kontakte table and deny if the email is not found. What I Have Tried: Verified the DJOSER settings point to the custom serializer. Added a print statement in validate_email to check if it's being called (it isn't). Any advice on what might be wrong or how to ensure my custom validation is used would be greatly appreciated. Thanks! -
Django ORM model default not applying in python queryset
I have the below Django ORM which represents a PostgreSQL view. For the field cost_requirement I have set the default value to 0. However the queryset object still populates with None if data is missing for this field. I have made all migrations and I just want the default to apply at the Python side (nothing to do with the database). From the Django documentation I understand I am using this argument correctly. Any suggestions why the default value of 0 is not being applied? class DashboardProduct(models.Model): date = models.DateField() product_id = models.CharField(max_length=50) base_l = models.FloatField(default=0) cost_requirement = models.FloatField(blank=False, null=False, default=0) book = models.CharField(max_length=100, blank=True, null=True) portfolio = models.CharField(max_length=100, blank=True, null=True) sales_5_pnl = models.FloatField(default=0) class Meta: managed = False db_table = 'view_dashboard_product' -
how to add product to my cart in django rest frame work drf
this is my model class Cart(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) created_at = models.DateTimeField(auto_now_add=True) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='cart_items') quantity = models.PositiveSmallIntegerField() class Meta: unique_together = [['cart', 'product']] this is my views class CartItemViewSet(ModelViewSet): http_method_names = ['get','post','patch','delete'] serializer_class = CartItemSerializer queryset = CartItem.objects.all() def get_queryset(self): cart_pk = self.kwargs['cart_pk'] return CartItem.objects.select_related('product').filter(cart_id = cart_pk).all() def get_serializer_class(self): if self.request.method == 'POST': return AddCartItemSerializer elif self.request.method == 'PATCH': return ChangeCartItemSerializer return CartItemSerializer def get_serializer_context(self): return {'cart_pk':self.kwargs['cart_pk']} class CartViewSet(CreateModelMixin, RetrieveModelMixin, DestroyModelMixin, GenericViewSet, ): serializer_class = CartSerializer queryset = Cart.objects.prefetch_related('items__product').all() lookup_value_regex = '[0-9a-f]{8}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?[0-9a-f]{12}' and my serializer class ProductSerializer(serializers.ModelSerializer): title = serializers.CharField(max_length=255, source='name') price = serializers.DecimalField(max_digits=6, decimal_places=2,source='unit_price') unit_price_after_tax = serializers.SerializerMethodField() class Meta: model = Product fields = ['id', 'title', 'price','category', 'unit_price_after_tax', 'inventory', 'description'] def create(self, validated_data): product = Product(**validated_data) product.slug = slugify(product.name) product.save() return product # def update(self, instance, validated_data): # instance.inventory = validated_data.get('inventory') # instance.save() # return instance def get_unit_price_after_tax(self , product): return round(product.unit_price * Decimal(1.09), 2) def validate(self, data): if len(data['name']) < 6: raise serializers.ValidationError('Product lentgh should be at least 6.') return data class CartProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['id', 'name', 'unit_price'] class ChangeCartItemSerializer(serializers.ModelSerializer): class Meta: model = CartItem fields = ['quantity'] class AddCartItemSerializer(serializers.ModelSerializer): class Meta: … -
ValueError: Field 'id' expected a number but got 'user'
i am fresher at django .i had tried my best for solving but i couldn't find the error .While making migration ,it shows this error " ValueError: Field 'id' expected a number but got 'user' ". enter image description here i am trying to create subfile i.e innerfile inside a folder ,but i am not able to do migrate my project -
how to set login_required in django project,i am not using django inbuild authentication login?
user cannot enter any page by entering the url of any page do i need to change anything in settings .py view.py for login to each dashboard def asset_login(request): if request.method == 'POST': username = request.POST.get('user_id') password = request.POST.get('password') try: user = UserTable.objects.get(username=username, password=password) if user: if user.status == 'inactive': messages.error(request, 'Your account is inactive.') return redirect('asset_login') request.session['name'] = user.name request.session['role'] =user.role if user.role == 'admin': return redirect('admin_dashboard') elif user.role == 'ciso': return redirect('ciso_dashboard') elif user.role == 'fnhead': return redirect('fnhead_dashboard') elif user.role == 'systemadmin': return redirect('systemadmin_dashboard') elif user.role == 'assetowner': return redirect('assetowner_dashboard') else: messages.error(request, 'Unknown user position') return redirect('asset_login') # Redirect to clear form and message except UserTable.DoesNotExist: messages.error(request, 'Invalid username or password') return redirect('asset_login') # Redirect to clear form and message return render(request, 'asset.html') urls.py urlpatterns = [ path('asset_login/', views.asset_login, name='asset_login'), path('admins/', views.admin_dashboard, name='admin_dashboard'), path('assetdb/', views.assetowner_dashboard, name='assetowner_dashboard'), view.py for dashboard def admin_dashboard(request): total_users = UserTable.objects.count() total_assets = AssetTable.objects.count() total_dept=Department.objects.count() total_emp=Employee.objects.count() name = request.session.get('name',None) role = request.session.get('role', None) try: admin_privileges = adminprivileges.objects.get() except ObjectDoesNotExist: admin_privileges = None context = { 'total_users': total_users, 'total_assets': total_assets, 'total_dept':total_dept, 'total_emp':total_emp, 'name':name, 'role':role, 'assetview': admin_privileges.assetview if admin_privileges else False, 'userview': admin_privileges.userview if admin_privileges else False, 'employeeview': admin_privileges.employeeview if admin_privileges else False, 'locationview': admin_privileges.locationview if admin_privileges … -
Django page doesn't display anything
My "News" page isn't working, it's saving info in database but doesn't display anything. Here's HTML: {% extends 'base.html' %} {% block content %} <h1 class = 'product'>News</h1> {% for item in new %} <div><br><strong><a href='/news/{{ item.id }}'>{{ item.title }}:</a></strong><br> {{ item.article }} <br>{{ item.views }} views</div> {% endfor %} {% endblock %} My views.py: def news(request): return render(request, 'news.html', {'news': New.objects.all()}) Models.py: class New(models.Model): title = models.CharField(max_length = 50) article = models.TextField() views = models.IntegerField(default = 0) user_views = models.ManyToManyField(to = User, blank = True) category = models.ForeignKey(to = NewCategory, on_delete = models.SET_NULL, null = True, blank = True, verbose_name = 'Категория') views_qty = models.IntegerField(default = 0) def __str__(self): return self.title -
How to use a single serializer to save multiple models
Problem : I’m unable to save the both models in database from a single serialzer. Description : I’m using djoser auth library for registration and authentication. for that i’m using custom django auth user and mapped it with userprofile model. Since i’m using userprofile along with the django user, i have to use custom register serializer. # My Models class CustomUser(AbstractUser): username = None email = models.EmailField(_("email address"), unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() class UserProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name="userProfile") user_guid = models.UUIDField( default=uuid.uuid4, unique=True, editable=False ) user_type = models.IntegerField(choices=UserType.choices(), default=UserType.BUYER) wallet_balance = models.FloatField() created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created_at' ] # Corrected the ordering syntax` `#My Serializer CustomUser = get_user_model() class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ['user_guid', 'user_type', 'wallet_balance', 'created_at', 'updated_at'] read_only_fields = ['user_guid', 'created_at', 'updated_at'] class CustomUserCreateSerializer(DjoserUserCreateSerializer): userProfile = UserProfileSerializer() class Meta: model = CustomUser fields = ['id', 'email', 'password', 'userProfile'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user_profile_data = validated_data.pop('userProfile') user = CustomUser.objects.create_user(**validated_data) UserProfile.objects.create(user=user, **user_profile_data) return user` AUTH_USER_MODEL = 'users.CustomUser' DJOSER = { 'SERIALIZERS': { 'user_create': 'users.v1.serializers.CustomUserCreateSerializer', 'user': 'users.v1.serializers.CustomUserCreateSerializer', 'current_user': 'users.v1.serializers.CustomUserCreateSerializer', } }` Error : raise ValueError( ValueError: Cannot assign “{‘user_type’: 1, ‘wallet_balance’: … -
Django REST Framework Does Not Show Image in React Frontend, But Titles and Other Text Are Showing
I am trying to build my blog site with Django as the backend and React as the frontend. For the REST API, I am using the Django Rest Framework library. I created a Blog model with an image field and set the media and static URLs in the settings.py file. Now, when I fetch the blogs in React with Axios, it doesn’t show the images, but I can see the blog titles and other fields. I ensured that the Django settings for media files are correctly configured. The image URLs are present in the API response when I inspect the network requests.enter image description here enter image description here enter image description here -
SQL Query Executor using Django
I am a beginner in software development, I am task to develop a web-based application, in which I use Django Web Framework, that can Execute SQL queries against a MS SQL Server Database, display the results of the query and log the details into the Django database (PostgreSQL), like timestamp, user, SQL Statement, errors, results etc, it is working. But, can you guys give me how to improve this? In my template, I use Ajax, and planning to use reactJS as frontend, but I am not really into it right now due to I need to learn it first. Objective: (1). I want to store the results in the session, retrieve it using ajax from the session and display the results. (2). but I want to add a unique ID using the generate_session_id() to that session data to identify that particular session data and retrieve it using ajax and display it the session data. (3). and to also enable the user to open new tab and run another SQL query executor. (3.1). Every time the page is reloaded or the page is ready, or the user open it in another tab, the unique session id should be different or renew … -
Django module not found
I'm very much a newbie trying to get a hold of Django. I am just getting started, trying to configure the URLs with an app. However, whenever I try to run the server, it tells me the urls module is not found, even when I use the absolute path. I've included some of my code below. from django.urls import include, path urlpatterns = [ path('custom_regions/', include("some\\absolute\\path\\placeholder.urls")), path('admin/', admin.site.urls), ] from django.urls import path from . import views urlpatterns = [ path('', views.index, name = 'index'), ] Considering I've been following the tutorial to a T, I'm not quite sure what I'm doing wrong.