Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django returning duplicates even though distinct() is used
I'm using django=4.1, python=3.8 & sqlite. What I want to do filter our the top five player points and unique players in a given month and present it in a template, there shouldn't be any duplicates. 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) And 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 When I run the below query it gives me the top 5 Player Points but it's not distinct, the player_ids are duplicates. It keeps repeating the same Player. q = PlayerPoint.objects.filter(points_ts__year=2023, points_ts__month=1, points__gte=2000) x = q.order_by('-points') … -
Restricting website access by client geolocation
I need to restrict access to a website because of countries regulations. I know that Hosting providers or CDNs/Webservers like Cloudflare or NGINX can do that for me and is probably the best approach (?) but I think only if the website needs to scale and since it has small expected traffic I'd like to just implement it myself for the start. This question is not about how to get the users IP or how to use geolocation APIs with that IP. It is about how to design the backend to deny or grant access to the website for the clients. Do I need to do it on every request to the server ? If yes should I just write middleware that rejects the request if it is a blocked coutry or put that logic somewhere else ? Or can I do it once and then just "remember" it somehow for that client (how reliable would that be/ could that be abused ?). I just dont want to build a super stupid design where I affect the performance of the backend just for a simple task like that. Thank you in advance. -
How can i access current session data outside django view function?
I am using SessionStore object to store session data, how can i get current session data from Session table without using pk as we dont know pk of record stored in table. Here is the code ldap.py from django.contrib.sessions.backends.db import SessionStore s = SessionStore() class LDAPPBackend(ModelBackend): def authenticate(self, *args, **kwargs): **s['memberOf']** = "Star Group" #**setting session** s.create() serializer.py from rest_framework import serializers from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from django.contrib.sessions.models import Session **s = Session.objects.get(pk="")** #**how can i know current logged in user session pk???** class TokenObtainPairPatchedSerializer(TokenObtainPairSerializer): def validate(self, attrs): data['attr'] = attrs **data['memberOf'] = s** # **How can i get current session data here??** return data How can i achieve this??? -
How to serve thumbnail image instead of full image on the articles listing page in Django?
I made a django powered website here it is https://www.endustri.io When you look the frontpage i serve the blog post feautered image in original size. And it causes the increase loading time. So i wanna serve 300x180 pixels the featured images of the posts. How can i make automatically 300x180 pixels images from my original images and how can i serve these images on the frontpage. When i looked the media file, i wanna see two images, one of is original and other image is 300x180 pixels. Here is my codes... views.py def frontpage(request): posts = Post.objects.order_by('-id') most = Post.objects.order_by('-num_reads')[:10] kat = Category.objects.all() f = Firma.objects.all().order_by('-id')[:15] p = Paginator(posts, 10) page = request.GET.get('page') sayfalar = p.get_page(page) context = { 'posts': posts, 'most': most, 'kat': kat, 'sayfalar': sayfalar, 'f': f, } return render(request, 'blog/frontpage.html', context) models.py class Post(models.Model): category = models.ForeignKey(Category, related_name="posts", on_delete=models.CASCADE) title = models.CharField(max_length=300) slug = models.SlugField(max_length=300) intro = models.TextField() body = tinymce_models.HTMLField() description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) featured_photo = models.ImageField(null=True, blank=True, upload_to="blog/") date_added = models.DateTimeField(auto_now_add=True) num_reads = models.PositiveIntegerField(default=0) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('detail', args=[str(self.slug)]) and frontpage.html {% for post in sayfalar %} <div class="card mb-3" style="max-width: 75%px;"> <div class="row g-0"> <div class="col-md-4"> <img … -
How to apply permissions on perform_create in ViewSet DRF
This is my View Set: class MyViewSet(ModelViewSet): serializer_class = MySerializer queryset = MyClass.objects.all() def get_serializer_class(self): if self.request.user.is_superuser: return self.serializer_class return serializers.MyUserSerializer def perform_create(self, serializer): employee = models.Employee.objects.get(user=self.request.user) serializer.save(employee=employee) I want to apply permission before perform_create, this perform_create() should only be called if a currently logged in user is not a super user. If a currently logged in user is a superuser, default perform_create function should be called. How to do that? -
Refused to apply style from '<URL>' because its MIME type ('text/html') pythonanywhere
Refused to apply style from '' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. i dont have any problem in vscode but when i hosted into pythonanywhere i cant even login into admin panel and the css from admin panel is not working -
Integration of Django-PayPal subscription based payment system
I am trying to implement a Subscription-based payment method in Django. I have tried to Integrate the subscription-based button as per the PayPal guidlines. Screenshot is attached for same. But after clicking on either button screen is blank, and nothing happens, screenshot is attached for the same. Here is my code for button integration. <div id="paypal-button-container-P-789654"></div> <script src="https://www.paypal.com/sdk/js?client-id=123456&vault=true&intent=subscription" data-sdk-integration-source="button-factory"></script> <script> paypal.Buttons({ style: { shape: 'pill', color: 'blue', layout: 'vertical', label: 'subscribe' }, createSubscription: function(data, actions) { return actions.subscription.create({ /* Creates the subscription */ plan_id: 'P-789654' }); }, onApprove: function(data, actions) { alert(data.subscriptionID); // You can add optional success message for the subscriber here } }).render('#paypal-button-container-P-789654'); // Renders the PayPal button </script> -
Django: starting server using a specific database out of multiple databases
I am trying to set up 2 databases in django. The second database is meant for testing purposes, so the 2 databases practically have the same models. My question is how to start the server using the second database. The steps I did for setting up the databases: I created a second app called 'testing', so now in my project root folder there is the app api (the real one) and testing (the app meant for the test database). Afterwards, added the same models from api/models.py to testing/models.py Created router for the first database and the second database: class AuthRouter: route_app_labels = {'auth', 'contenttypes', 'admin', 'sessions'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'default' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'default' return None def allow_migrate(self, db, app_label, model_name = None, **hints): if app_label in self.route_app_labels: return db=='default' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None class SpotTesting: route_app_labels = {'spot_testing'} def db_for_read(self, model, **hints): if model._meta.app_label == "spot_testing": return 'test_db' return None def db_for_write(self, model, **hints): if model._meta.app_label == "spot_testing": return 'test_db' return None def allow_relation(self, obj1, obj2, **hints): """ … -
Forbidden (403) CSRF verification failed - Error with Docker, Django and Nginx
I am new to docker. Starting from a Django project (Django 4.0), I am using Docker to side by side with Nginx. I used a docker-compose.yml file and used a custom configuration of Nginx, and everything works. Only when I go to the login screen and click the "Login" button it comes up "Forbidden (403) CSRF verification failed. Request aborted.". The code inside login.html is like this <form method="post">{% csrf_token %} {{ form|crispy }} <button class="btn btn-success ml-2" type="submit">Log In</button> Thanks in advance! -
how to fix roll up error while building vue apps?
i want to deploy simple personal website using vue but when i try to npm run build this error come up help me please... i try deleting the image but onother similiar error come's up error during build: RollupError: Could not resolve "../img/react%202.png" from "src/component/avatarmenu.vue" at error (file:///C:/Users/adity/OneDrive/Documents/LATIHAN/personal-w-vue/node_modules/rollup/dist/es/shared/rollup.js:2041:30) at ModuleLoader.handleInvalidResolvedId (file:///C:/Users/adity/OneDrive/Documents/LATIHAN/personal-w-vue/node_modules/rollup/dist/es/shared/rollup.js:23137 :24) at file:///C:/Users/adity/OneDrive/Documents/LATIHAN/personal-w-vue/node_modules/rollup/dist/es/shared/rollup.js:23099:26 -
Django app not able to find database engine when engine is specified
I have tried everything I can think of to run my initial migrations and get my django app up. I am currently getting this error: Traceback (most recent call last): File "manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python3/dist-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python3/dist-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/lib/python3/dist-packages/django/core/management/commands/dbshell.py", line 22, in handle connection.client.runshell() File "/usr/lib/python3/dist-packages/django/db/backends/dummy/base.py", line 20, in complain raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. But this is the DATABASES var in my settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } The db.sqlite3 file is at the location specified in the 'NAME' key. The app folder is in a subdirectory and uniquely named. The BASE_DIR var is constructed correctly and not causing the location string in the NAME key to be malformed. The models.py file is in the /app folder subdirectory. I am completely out of ideas on how to get this to work and considering giving up on making this project altogether. Please help. … -
Use HTML-template from other app, in same project (Django)
I have a project wich contains two apps User and Accounting. Since all of their HTML-templates should extend from the same base.html template, I made a third app called Shared, and my accounting/base.html and user/base.html would then extend from shared/base.html like {% extends "shared/base.html" %} {% block content %} <div>Hello world</div> {% endblock content %} but that does not work, since Django looks in <app>/templates/shared/base.html. Can this be done without having to just duplicate base.html and have the same file in Accounting and User? -
I have an error in django template for loop
I have an error in django template for loop. My code: <div class="form-group col-md-4 form-field"> <label>Year</label> <select name="year" id="year" name="year"> {% for y in range(1980, (datetime.datetime.now().year + 1)) %} <option value="{{ y }}">{{ y }}</option> {% endfor %} </select> </div> My error: 'for' statements should use the format 'for x in y': for x in y range(1980, (datetime.datetime.now().year + 1)) Please help me to resolve this issue. Please help me to resolve this issue. Please help me to resolve this issue. -
update value certain time later using django appscheduler
I want to update a value every day at a certain time later. I wrote my models and views look like models.py class InvestmentRequest(models.Model): user = models.OneToOneField(User, related_name=“investment_request”, on_delete=models.CASCADE) profit = models.DecimalField(max_digits=15, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user.username}-{self.amount}" def increase_balance(self, profit ): self.profit += decimal.Decimal(profit ) self.save() def save(self, *args, **kwargs): super().save(*args, **kwargs) views.py scheduler = BackgroundScheduler() job = None def tick(): print(‘One tick!’) # roi_profit() --- any way like this def start_job(): global job job = scheduler.add_job(tick, 'interval', seconds=3) try: scheduler.start() except: pass I used here “appscheduler” library because my requirement is minimal, it’s not a complex configuration like celery. Is there any way to run ‘roi_profit’ views at a certain time every day? Here ‘tick’ function runs very smoothly because it is a normal function. But I can’t call the views function because it’s a required request. And without request, I can’t get any value from request.user. It’s necessary. So this way how I can update my model value at a certain time later every day. Over a couple of days I’m struggling with it but couldn’t find the exact solution. Any suggestions will be appreciated. Thanks. -
Why is my create button not redirecting to the form? (For django)
I am new to Django and am trying to make an online journal, and the server runs fine, but when I press the create button, it does not redirect to the form even though a POST request is being sent. screenshot of the create page. I'm not sure why. This is the code: views.py: from django.shortcuts import render, redirect, get_object_or_404 from ejournal.models import Journal from ejournal.forms import JournalForm def make_entry(request): if request.method == "POST": entry = JournalForm(request.POST, request.FILES) if entry.is_valid(): entry.save() return redirect('list_journals') else: entry = JournalForm() context = { 'entry':entry } return render(request, 'ejournal/create.html', context) def delete_entry(request, id): entry = get_object_or_404(Journal, id=id) if request.method == "POST": entry.delete() return redirect('list_journals') context = { 'object':object } return render(request, 'journal/delete.html',context) def list_journals(request): entries = Journal.objects.all() context = { 'entries': entries } return render(request, 'ejournal/list_journals.html',context) def journal_detail(request, id): journal = Journal.objects.get(id=id) context = { 'journal':journal } return render(request, 'journal/journal_detail.html', context) forms.py from ejournal.models import Journal from django.forms import ModelForm class JournalForm(ModelForm): class Meta: model = Journal fields = ['name','title','text','image'] models.py from django.db import models class Journal(models.Model): name = models.CharField(max_length=20) title = models.CharField(max_length=50) text = models.TextField(max_length=1000) date = models.DateField(auto_now_add=True) image = models.FileField(upload_to='') archived = models.BooleanField(default=False) def __str__(self): return self.name base.html {% load static %}<!DOCTYPE … -
Python, Django, HTMX, is it possible to save data, when a user clicks <button>
When a user click <button> on index page, can save data immediately? views.py def index(request): ... ... context = { ... } response = render(request, 'docu/index.html', context) ### Save visitors' IP and Keywords to KeyLOG table ### ip = request.META.get('REMOTE_ADDR') keywords = request.META.get('HTTP_REFERER', '') keylog = KeylogForm(request.GET) keylog = keylog.save(commit=False) keylog.ipaddr = ip keylog.keyquery = keywords keylog.svae() return response def keylog(request): if request.method == "GET": keylog_list = list(Keylog.objects.all().order_by()\ .values('idpaddr', 'keywords', 'tel_log', 'regtime')) return JsonResponse(keylog_list, safe=False) return JsonResponse({'message':'error'}) forms.py class KeylogForm(forms.ModelForm): class Meta: model = Keylog fields = ['ipaddr','keyquery','tel_log'] models.py class Keylog(models.Model): ipaddr = models.CharField(max_length=32,null=True, blank=True) #save IP addr keyquery = models.CharField(max_length=128,null=True, blank=True) #save keywords tel_log = models.CharField(max_length=256,null=True, blank=True) #save tel_log regtime = models.DateTimeField(auto_now_add=True) #created time Currently, it makes table as below; Ipaddr keyquery tel_log regtime 192.168.x.yy ?query=apple 2023.01.01.12.24.56 192.168.a.bb ?query=banana 2023.01.01.11.22.33 I hope to save Tel_log data in the above table, when a user clicks <butto>...</button>. So I made an index.html as below; index.html <div id="tel_log"> <button class="btn btn-danger"> hx-get="keylog/" hx-vals="[tel_log='CALL']" hx-trigger="click"> Phone NUMBER </button> </div> My expectation is that when I clicked [Phone NUMBER] on the index page, "CALL" is appeared on the "tel_log" column of the above table, but it didn't work, just shows {message:error} I'm a newbie … -
Getting error in Django Custom user model treating every created user as staff user why?
This is my code for Custom user model in Django app i want to make a ecommerce app but when i am creating a superuser in terminal and using that for login insted of making a super user the admin console is treating every account as staff account and even correct email and password is not working? can any one help from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager # Create your models here class MyAccountManager(BaseUserManager): def create_user(self,first_name,last_name,username,email,password=None): if not email: raise ValueError('User must have an email address') if not username: raise ValueError('User must have an username') user = self.model( email=self.normalize_email(email), username = username, first_name = first_name, last_name = last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,first_name,last_name,email,username,password): user = self.create_user( email=self.normalize_email(email), username = username, first_name = first_name, last_name = last_name, ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superadmin = True user.save(using=self._db) return user class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50,unique=True) email = models.EmailField(max_length=100, unique=True) phone_number = models.CharField(max_length=50) #required date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superadmin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username','first_name','last_name'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm,obj=None): return … -
Django Form with ForeignKey field NOT NULL constraint failed Error
Each model is chain-linked to the previous model. I make one form to fill in, since all the models are linked. When I try to link a model address to a project, an error appears NOT NULL constraint failed: crm_project.address_id /crm/views.py, line 39, in add_project form_project.save() Models class City(models.Model): obl = models.CharField(max_length=255, choices=REGIONS, default="24", verbose_name="Регион") name = models.CharField(max_length=128, verbose_name="Город") population = models.IntegerField() def __str__(self): return self.name class Address(models.Model): city = models.ForeignKey(City, on_delete=models.PROTECT, verbose_name="Город") street = models.CharField(max_length=255, verbose_name="Улица") numb = models.CharField(max_length=64, verbose_name="Номер дома") def __str__(self): return f"{self.street}, {self.numb}" class Project(models.Model): manager = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name="Сотрудник") address = models.ForeignKey(Address, on_delete=models.PROTECT, verbose_name="Адрес") # another fields class ProjectDetail(models.Model): project = models.OneToOneField(Project, on_delete=models.CASCADE, verbose_name="Проект") # another fields Forms class AddressForm(forms.ModelForm): class Meta: model = Address fields = ["city", "street", "numb"] def __init__(self, *args, **kwargs): city = kwargs.pop("city", "") super(AddressForm, self).__init__(*args, **kwargs) self.fields["city"] = forms.ModelChoiceField(queryset=City.objects.all()) class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ["file", "sq", "rent_tax"] class ProjectDetailForm(forms.ModelForm): class Meta: model = ProjectDetail exclude = ['project', 'comment', 'resume', 'complite', 'created_at'] Views def add_project(request): form_address = AddressForm(request.POST or None) form_project = ProjectForm(request.POST or None) form_detail = ProjectDetailForm(request.POST or None) if request.method == 'POST': if form_address.is_valid() and form_project.is_valid() and form_detail.is_valid(): address = form_address.save(commit=False) form_project.manager = request.user form_project.address … -
Django Variable Re-evaluation in Template
So let's say in my template, I use: <td> {{ model1.column1.column11.code1 }} </td> <td> {{ model1.column1.column11.code2 }} </td> <td> {{ model1.column1.column11.code3 }} </td> <td> {{ model1.column1.column11.code4 }} </td> <td> {{ model1.column1.column11.code5 }} </td> <td> {{ model1.column1.column11.code6 }} </td> <td> {{ model1.column1.column11.code7 }} </td> and for comparison: {% with col=model1.column1.column11 %} <td> {{ col.code1 }} </td> <td> {{ col.code2 }} </td> <td> {{ col.code3 }} </td> <td> {{ col.code4 }} </td> <td> {{ col.code5 }} </td> <td> {{ col.code6 }} </td> <td> {{ col.code7 }} </td> {% endwith %} My questions are: For the first code, does it imply that the model1.column1.column11 will be queried by Django 7 times? For the second code, will the usage of with col=model1.column1.column11 can make the template rendering faster, as the query of model1.column1.column11 is only once from the {% with %} block, and just get the variables from the col? Are there any alternatives to both these approaches? Currently, my SQL table consists of less than 1000 rows so any performance issues may not be seen. But, my concern is when the SQL table is large enough and will require many optimization on the query. -
FieldError: Unsupported lookup 'iexact' for EncryptedCharField or join on the field not permitted, perhaps you meant iexact or exact?
class UserDataIdModel(models.Model): user_id = encrypt(models.CharField(default=user_pk, primary_key=True, max_length=255, unique=True)) name = encrypt(models.CharField(max_length=100)) email = encrypt(models.EmailField(max_length=100)) phone = encrypt(models.CharField(max_length=100)) dob = encrypt(models.DateField()) created_dt = models.DateTimeField(auto_now_add=True) def data_delete(request, id): print('id:------------->', id) model_obj = UserDataIdModel.objects.get(user_id__iexact=id) print(model_obj) model_obj.delete() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) How to delete or get Records when data is EncryptedCharField.... -
problem in form not show in templates - django
problem in form not show django don't show form in template I applied everything in the Django tutorial, but foam does not appear, but I did not know the reason despite my research add_book.html {% extends 'base.html' %} {% block content %} <h1>add book </h1> <form method="post"> {% csrf_token %} <hr> {{form}} <hr> <a href="" type="submit">submit</a> </form> {% endblock content %} in forms from django import forms from .models import book class book_form(forms.Form): class meta: model = book fields = '__all__' in views from .models import * from .forms import book_form def addbook(request): bookform = book_form() context = {'form' : bookform} return render(request, 'add_book.html', context) in url path('book/add', views.addbook, name="addbook"), -
Login doesn't work for an ordinary user in Django DRF
I added the ordinary user through admin app but when i try to login to the site nothing happens. Maybe there is something wrong with my custom user model. Or it maybe something else? The custom user models' Models.py: from django.db import models from django.contrib.auth import models as auth_models class UserManager(auth_models.BaseUserManager): def create_user( self, first_name: str, last_name: str, email: str, password: str = None, is_staff=False, is_superuser=False, ) -> "User": if not email: raise ValueError("User must have an email") if not first_name: raise ValueError("User must have a first name") if not last_name: raise ValueError("User must have a last name") user = self.model(email=self.normalize_email(email)) user.first_name = first_name user.last_name = last_name user.set_password(password) user.is_active = True user.is_staff = is_staff user.is_superuser = is_superuser user.save() return user def create_superuser( self, first_name: str, last_name: str, email: str, password: str ) -> "User": user = self.create_user( first_name=first_name, last_name=last_name, email=email, password=password, is_staff=True, is_superuser=True, ) user.save() return user class User(auth_models.AbstractUser): first_name = models.CharField(verbose_name="First Name", max_length=255) last_name = models.CharField(verbose_name="Last Name", max_length=255) email = models.CharField(verbose_name="Email or Phone Number", max_length=255, unique=True) password = models.CharField(max_length=255) username = None objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] Admin.py: rom django.contrib import admin from . import models class UserAdmin(admin.ModelAdmin): list_display = ("id", "first_name", "last_name", "email") … -
how to solve the problem of DataTables warning: table id=table_detail - Requested unknown parameter 'admin' for row 0, column 0
Django html Error Result Please kindly help me to fix it. I want to put the JSON data into datatables. -
some parts of my form is rendering correctly but some arent Django
I am creating a ticket app in my django project. When I create a ticket and submit, parts of the form render correctly in the frontend except three fields. These are the ticket.name, category.name and ticket.description, in the frontend these fields display as 'None' but everything else renders as its supposed to in the frontend. I also checked my admin page and i see that neither the Ticket nor the Category get created properly. I'm not quite sure how to proceed. Here's what i have so far models.py class Category(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name or '' class Ticket(models.Model): STATUS = ( (True, 'Open'), (False, 'Closed') ) PRIORITIES = ( ('None', 'None'), ('Low', 'Low'), ('Medium', 'Medium'), ('High', 'High') ) TYPE = ( ('Misc', 'Misc'), ('Bug', 'Bug'), ('Help Needed', 'Help Needed'), ('Concern', 'Concern'), ('Question', 'Question') ) host = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, related_name='host') category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='category') name = models.CharField(max_length=200, null=True) status = models.BooleanField(choices=STATUS, default=True) priority = models.TextField(choices=PRIORITIES, default='None', max_length=10) type = models.TextField(choices=TYPE, default='Misc', max_length=15) description = RichTextField(null=True, blank=True) # description = models.TextField(null=True, blank=True) participants = models.ManyToManyField(CustomUser, related_name='participants', blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name or '' … -
Get the see only particular station which create by the login user in Django
I Tried to create Slot of station for EV Charging Booking Webiste. If i tried to creating slot of praticular station but I suggest all station which created by other of all. I should see the particular station has the created by login user in Slot in django Here is my Station list Django reflate 3 station from my database My Station 2 and 3 but I can see all 3 station Help to Slove my Query here my Slotviews.py class SlotCreateView(LoginRequiredMixin, CreateView): model = Slot fields = ('slot_name', 'per_unit_price', 'current_status','station') template_name = 'add_slot.html' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def get_success_url(self): return reverse('view_slot') here is slot models.py class Slot(models.Model): CURRENT_STATUS_CHOICE = ( ("AVAILABLE", "AVAILABLE"), ("OCCUPIED", "OCCUPIED") ) slot_id = models.AutoField(primary_key=True) station = models.ForeignKey(Station, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) slot_name = models.CharField(max_length=30) per_unit_price = models.DecimalField(max_digits=7, decimal_places=2) current_status = models.CharField(max_length=20, choices=CURRENT_STATUS_CHOICE, default="AVAILABLE") deleted = models.IntegerField(default=0, unique=False) def __str__(self): return f"{self.slot_name}"