Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
For what do we need object storage spaces for django application in production?
This is first time that I am hosting some of application on server. Its a Django application that is being served on Digital Ocean. I am seeing couple of toturials that are suggesting me to use S3 storage spaces for serving static and media files. I am not getting why do I need a separate storage space? Can't django own static and media folder serve the purpose? Can anyone clearify? -
Django how to show audio video and image in html template?
`class Post(models.Model): post_media = models.FileField(blank = True, null = True, upload_to = 'post_media_store') title = models.CharField(max_length = 100,) description = models.CharField(blank=True, max_length = 800) location = models.CharField(blank = True, max_length = 100) date_posted = models.DateTimeField(default = timezone.now) original_poster = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE) def __str__(self): return self.title -
Django Rest Framework, user models getting error
My project is simple blog app where users can post,comment and like posts. I used Django default user registration page, later I add Djoser (third party token authentication for Django rest framework) with custom user model, it result in crash, please look into this please note that if I avoid custom user for Djoser,my project works fine,ie I am able to register using token and session authentication FORMS.PY #for Django's default register view from django import forms #from django.contrib.auth.models import User from .models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields=['username','email','phone','first_name','last_name','password1','password2'] MODELS.PY # Djoser Custom user model from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings class User(AbstractUser): email = models.EmailField(verbose_name='email' ,max_length=223,unique=True) phone=models.CharField(null=True,max_length=11) REQUIRED_FIELDS = ['username','phone','first_name','last_name'] #USERNAME_FIELD = 'email' def get_username(self): return self.email -
--noinput error when deploying Django project to Heroku
I am deploying my Django App on Heroku. I have followed quite a few tutorials, including the Heroku official one but with no luck. This the error message I get: Successfully installed Django-3.0.6 asgiref-3.2.7 certifi-2020.4.5.1 chardet-3.0.4 dj-database-url-0.5.0 django-crispy-forms-1.9.0 gunicorn-20.0.4 idna-2.9 psycopg2-2.8.5 pytz-2020.1 requests-2.23.0 sqlparse-0.3.1 urllib3-1.25.9 whitenoise-5.0.1 remote: -----> $ python Pur-Beurre/manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "Pur-Beurre/manage.py", line 21, in <module> remote: main() remote: File "Pur-Beurre/manage.py", line 17, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 104, in collect remote: for path, storage in finder.list(self.ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 130, in list remote: for path in utils.get_files(storage, ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files remote: directories, files = storage.listdir(location) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 316, in listdir remote: for entry in os.scandir(path): remote: NotADirectoryError: [Errno 20] Not a directory: '/tmp/build_d6b6d9fab362a0d21ea87ebd0f7a85e2/Pur-Beurre/pur_beurre/settings.py/static' remote: remote: ! Error while running '$ python Pur-Beurre/manage.py collectstatic --noinput'. remote: See traceback … -
Django pages not getting paginated
I'm using Django-filters to filter results. The filter is working correctly, but now the pagination is not working. It's being rendered, but now all the products are being displayed in one page. I was using paginate_by = 6 as it is a class based view. Even after filtering results, for example there are 8 products matching the filter, everything is being displayed in one single page. Why is it not working? Can anyone please help me out? Thanks in advance! My views.py: class homeview(ListView): model = Item template_name = 'products/home.html' paginate_by = 6 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = ItemFilter(self.request.GET, queryset=self.get_queryset()) return context My index.html: <div class="card mb-4"> <div class="card-body"> <div class="container"> <form method="GET"> {{ filter.form|crispy }} <button type="submit" class="btn btn-primary mt-4">Filter</button> </form> </div> </div> </div> <h1>List Of Items</h1> <div class="row mb-4"> {% for item in filter.qs %} <div class="col-lg-4"> <img class="thumbnail" src="{{ item.image_url }}"> <div class="box-element product"> <h6><strong>{{ item.title }}</strong></h6> <h6 class="text-success">Category - {{ item.get_category_display }}</h6> <hr> </div> </div> {% endfor %} </div> -
not showinf models value in html template django
I just created a one app in which i created a db named as Quizz. User come and give a test on website. The answers and username get saved in db columns. Not able to show this table info in html page html page {% for post in data %} {{Quizz.ans1}} {% endfor %} views.py def test(request): if request.method=='POST': user = request.user ans1=request.POST['sky'] ans2=request.POST['cricket'] ans3=request.POST['river'] x=Quizz.objects.create(user=user,ans1=ans1,ans2=ans2,ans3=ans3) x.save() return redirect('home') return render(request,'test.html',) models.py class Quizz(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ans1=models.CharField(max_length=20,default='') ans2=models.CharField(max_length=20,default='') ans3=models.CharField(max_length=20,default='') class Meta: db_table = 'quizz' -
Clickable row in Table
I have a backend written in Django and I'm using REST API for connecting it with React frontend. I have a table that is fulfilled with data that I'm getting from my API. The question is how to make those rows clickable so when I click on table row I get more info about what that row represents. I would need to open a new page which will display more information about that specific row. -
how to Set default value for author field in django form using views.py
Im developing a social website I have problem in creating new post I don't know how set author name as default of logged in user it always give option for all the previously logged in users I want to make it default for the logged in user I don't know how to set default value for that author field views.py class CreatePostView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post forms.py class PostForm(forms.ModelForm): class Meta(): model = Post fields = ('author','title','text','Post_image') widgets = { 'title':forms.TextInput(attrs={'class':'textinputclass'}), 'text':forms.Textarea(attrs={'class':'editable medium-editor-textarea postcontent '}) } modesls.py class Post(models.Model): author = models.ForeignKey('auth.User',on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() Post_image= models.ImageField(upload_to='media' ,blank=True ,editable=True) created_date = models.DateTimeField(default=timezone.now()) published_date = models.DateTimeField(blank=True,null=True) -
(Django) Creating a simple website with account signup/login WITHOUT using the basic Django auth/admin/csrf modules
I am supposed to make a basic Django app that receives user info(username, password, name, email) and checks they exist in the database already and returns 200 status if the info matches the one in the database. Also, if the database does not have such info, it should receive it on its signup page and stores in its database. The tricky part is that I am not supposed to use the Django functionalities like auth or admin or csrf. So basically, I have to emulate the Django functions from scratch. Below are what I have been working on so far. The project name is second_try directories account/models.py from django.db import models class Users(models.Model): username = models.CharField(max_length = 50) password = models.CharField(max_length = 300) email = models.CharField(max_length = 50) name = models.CharField(max_length = 50) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.objects.all() account/views.py import json from django.views import View from django.http import JsonResponse from .models import Users from django.views.generic import TemplateView class HomeView(TemplateView): template_name = 'index.html' class SignUp(TemplateView): template_name = 'signup.html' class AccountView(TemplateView): def post(self, request): data = json.loads(request.body) Users( username = data['username'], password = data['password'], email = data['email'], name = data['name'] ).save() return JsonResponse({'message':'SUCCESS'}, … -
How do I get the results of a multiple choice field from Django?
I set up a model multiple choice field, where a user can select multiple choices. I want to be able to get the choices that a user selected when filling out the form. What can I call to get the results that the user picked? Also, how would I iterate over those results (what does it return)? Here's the field: CHOICES = MyMultipleModelChoiceField(queryset=MODEL.objects.all(), widget=forms.CheckboxSelectMultiple, required=False) Thanks! -
How to filter in Django DB based on calculations from different tables
I have 3 models from 3 different tables: class Profiles(models.Model): player_name = models.CharField(max_length=150) player_surname=models.CharField(max_length=200) class Meta: db_table='profiles' class Results_2019(models.Model): player_name = models.CharField(max_length=150) profiless=models.ManyToManyField(Profiles) first_score=models.DecimalField(decimal_places=2,max_digits=1000) second_score=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='results_2019' class Results_2018(models.Model): player_name = models.CharField(max_length=150) profiless=models.ManyToManyField(Profiles) first_score=models.DecimalField(decimal_places=2,max_digits=1000) second_score=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='results_2018' The database is static. Player in all three models have the same names =['Alex','Chandler','Zach'] and they all have data belonging to them for all columns ( first_score,second_score) Profiles database look like : id player_name player_surname 1 Alex Chapman 2 Chandler Wellington 3 Zach Berg Results_2019 database look like : id player_name first_score second_score 1 Alex 70 68 2 Chandler 60 62 3 Zach 90 85 Results_2018 database look like : id player_name first_score second_score 1 Alex 78 81 2 Chandler 56 66 3 Zach 97 95 I want to apply statictic analysis to players which involves math calculation based on values from Results_2019 and Results_2018 such as i want to get: - players whos growth in first_score and second_score in 2019 and in 2018 were more than 20% and then get the name and surnames who met these criteria and print in template. The below formula of criteria though does not work i show as guidance of what i want to … -
Filtering django querysets
In a project I have a view wich displays in the browser as a searchbar to search recipes. I think there is a better way then how I'm doing it right now, but have no idea how. If I don't do what I'm doing right now, I get the error that you can't filter with None. I know I could use a try exept but then none of the values may be None or an error is raised. class SearchResultListViewOther(ListView): model = Recipe template_name = 'recipes/search_other.html' extra_context = { 'time': time, 'categorie': categorie, 'continent': continent, } def get_queryset(self): """ Filter out recipes by some other params like the title """ # Can not filter on None so set a value if no search params were given title = self.request.GET.get('title') if not title: title = '0' time_recipe = self.request.GET.get('time') if not time_recipe: time_recipe = 0 continent_recipe = self.request.GET.get('continent') if not continent_recipe: continent_recipe = '0' object_list = Recipe.objects.filter( Q(title__icontains=title) | Q(time__lte=time_recipe) | Q(continent__exact=continent_recipe) ) return object_list -
Docker Pytest containers stay up after completing testing process
I've set my django project and now I'm trying to test it with pytest. What is issue running pytest withing my containers doesn't kill it at the end of the process. So at the end of day I'm stuck with multiple running containers from pytest and often postgreSql connection problems. My docker-compose file: version: '3' services: license_server: build: . command: bash -c "python manage.py migrate && gunicorn LicenseServer.wsgi --reload --bind 0.0.0.0:8000" depends_on: - postgres volumes: - .:/code environment: DATABASE_NAME: "${DATABASE_NAME}" DATABASE_USER: "${DATABASE_USER}" DATABASE_PASSWORD: "${DATABASE_PASSWORD}" DATABASE_PORT: "${DATABASE_PORT}" DATABASE_HOST: "${DATABASE_HOST}" env_file: .env ports: - "8000:8000" restart: always postgres: build: ./postgres volumes: - ./postgres/postgres_data:/var/lib/postgresql/data/ environment: POSTGRES_PASSWORD: postgres DATABASE_NAME: "${DATABASE_NAME}" DATABASE_USER: "${DATABASE_USER}" DATABASE_PASSWORD: "${DATABASE_PASSWORD}" DATABASE_PORT: "${DATABASE_PORT}" DATABASE_HOST: "${DATABASE_HOST}" command: "-p 8005" env_file: .env ports: - "127.0.0.1:8005:8005" restart: always nginx: image: nginx:latest container_name: nginx1 ports: - "8001:80" volumes: - .:/code - ./config/nginx:/etc/nginx/conf.d depends_on: - license_server What I want to achieve is automatically closing containers after the testing process is finished. -
RabbitMQ Pika and Django Channels websocket
I am using Django Channels and RabbitMQ pika, for the first time. I am trying to consume from RabbitMQ queue. I am using Django Channels AsyncConsumer to group send it to everyone connected in the websocket. User type 1 : Can create a task User type 2 : Can accept the task. Use case : When user type 1 creates the task it is published in the rabbitmq. When it is consumed from the queue, it has to be group-sent to frontend. And when the user type 2 accepts the task other instances of user type 2 cannot accept the same and we consume from the queue again and send the next task in the queue to everyone. I have created the connection in a different thread using sync_to_async I am appending it to an in-memory list from the callback function. And whenever someone accepts I just pop it out of the list and acknowledge the queue. class AcceptTaskConsumer(AsyncConsumer): body = [] #IN MEMORY LIST delivery = {} #To store ack delivery_tag async def websocket_connect(self, event): print("AcceptTaskConsumer connected", event) AcceptTaskConsumer.get_task() #STARTS Queue listener in new thread self.room_group_name = "user_type_2" await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.send({ "type": "websocket.accept" }) async … -
How to optimize my code and the database access?
I'm creating a sme budingeting application, where I have the necessity to manage a lot of data ( huge list of products, balance sheet table etc.). I want to have an efficient and optimized code, respecting the DRY principle and less querysets possible to the database. Ad example this code in my views.py is it efficient and optimized? def conto_economico(request): # Creazione tabella materie prime, sussidiarie, di consumo e merci defaults = list(0 for m in range(12)) elements = dict() for conto_id, year, month, totale in(Materiale.objects.values_list('conto__nome', 'data__year', 'data__month').annotate(totale=ExpressionWrapper(Sum(F('quantita') * F('prezzo')), output_field=FloatField())).values_list('conto__nome', 'data__year', 'data__month', 'totale').order_by("conto_id")) : if conto_id not in elements.keys(): elements[conto_id]=list(defaults) index=month-1 elements[conto_id][index]=totale total_elements={'Per materie prime, sussidiarie, di consumo e di merci': [sum(t) for t in zip(*elements.values())],} I utilize this code for a lot of model to create my tables, but I think that are not efficient. -
AWS Django project throws AttributeError at /contact when sending a form
I've been working on my first website with django, it's deployed to aws with zappa. The page is using Lambda, S3, Apigateway and cloudfront. When I get the api url from my terminal after deployment/update the form works fine. But when I try to send the form from my actual website urls I've set up in aws the website throws the following error: AttributeError at /contact 'list' object has no attribute 'lower' Request Method: POST Request URL: https://asdasdasd.execute-api.eu-west-1.amazonaws.com/my_bucket/contact Django Version: 2.1 Exception Type: AttributeError Exception Value: 'list' object has no attribute 'lower' Exception Location: /var/task/django/utils/http.py in is_same_domain, line 278 Python Executable: /var/lang/bin/python3.8 Python Version: 3.8.2 Python Path: ['/var/task', '/opt/python/lib/python3.8/site-packages', '/opt/python', '/var/runtime', '/var/lang/lib/python38.zip', '/var/lang/lib/python3.8', '/var/lang/lib/python3.8/lib-dynload', '/var/lang/lib/python3.8/site-packages', '/opt/python/lib/python3.8/site-packages', '/opt/python', '/var/task'] Server time: Thu, 7 May 2020 06:13:04 +0000 My settings.py looks like this: """ Django settings for sciar_website project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ['SECRET_KEY'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ['DEBUG'] # EMAIL_HOST = ALLOWED_HOSTS = ['127.0.0.1', '(my_api_numbers).execute-api.eu-west-1.amazonaws.com', 'mywebsite.co/'] # Application definition INSTALLED_APPS = [ … -
Having trouble when migrating changes to the database - Python/Django
I was making some changes to the database in my project but i am facing some problems, it appears to not be a column in one of my tables but there it is, don't know what may be the cause of the problem, i'm not sure if it has to be with the onetoonefield relationships or what just broke it up entirely. Models from django.db import models # Create your models here. class BloodType(models.Model): Tipo = models.CharField(max_length=100) def __str__(self): return self.Tipo class Gender(models.Model): Genero = models.CharField(max_length=100) def __str__(self): return self.Genero class Nationality(models.Model): Nacionalidad = models.CharField(max_length=100) def __str__(self): return self.Nacionalidad class CivilStatus(models.Model): Estado = models.CharField(max_length=100) def __str__(self): return self.Estado class InsuranceCompany(models.Model): Compania = models.CharField(max_length=200) def __str__(self): return self.Compania class Policy(models.Model): Tipo_Poliza = models.CharField(max_length=256) def __str__(self): return self.Tipo_Poliza class Insurance(models.Model): Aseguradora = models.OneToOneField(InsuranceCompany,on_delete=models.DO_NOTHING) Tipo_de_Poliza = models.OneToOneField(Policy, on_delete=models.DO_NOTHING) Numero_de_poliza = models.CharField(max_length=100) Vencimiento = models.DateField() def __str__(self): return str(self.Aseguradora) + ' ' + str(self.Tipo_de_Poliza) class Patient(models.Model): Codigo = models.CharField(max_length=15) Nombre = models.CharField(max_length=100) Apellidos = models.CharField(max_length=200) Fecha_Nacimiento = models.DateField() Telefono = models.CharField(max_length=25,blank=True) Correo = models.EmailField(blank=True) Expediente = models.CharField(max_length=200, blank=True) Tipo_sangre = models.OneToOneField(BloodType,on_delete=models.DO_NOTHING) Peso = models.PositiveIntegerField() Estatura = models.PositiveIntegerField() Genero = models.OneToOneField(Gender,on_delete=models.DO_NOTHING) Nacionalidad = models.OneToOneField(Nationality,on_delete=models.DO_NOTHING) Estado_civil = models.OneToOneField(CivilStatus,on_delete=models.DO_NOTHING) Ocupacion = models.CharField(max_length=100,blank=True) Lugar_de_procedencia = models.CharField(max_length=100) Lugar_de_residencia = … -
How to add JS file in Django Admin just before the body tag
I am inserting two scripts into Djnago Admin as follows: class TutorialAdmin(admin.ModelAdmin): class Media: js = ( 'tutorials/js/ckeditor.js', 'tutorials/js/custom.js', ) formfield_overrides = { models.TextField: {'widget': Textarea( attrs={'id': 'custom_textarea'})} } Notice the formfield_overrides where I am adding an id custom_textarea to textarea tags so that I can get them later via javascript. If we look at my custom.js file: ClassicEditor .create( document.querySelector( '#custom_textarea' ) ) .catch( error => { console.error( error ); } ); This is the file which gets the element with id of custom_textarea. But the problem is that these files are added in the head tag so they run as soon as the page loads (before the textarea is rendered). I get the following error in the Chrome console: TypeError: Cannot read property 'appendChild' of null Is there a way where I can instruct Django to inject the custom.js just before the body tag? I know of a solution where I could edit my base.html in admin app. But I am wondering if there is a Django Way of doing this! Thanks. -
How to add user profile attributes to custom user model ( from AbstractUser ) in django admin panel? - StackInline
I saw an example in django document like this; from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from my_user_profile_app.models import Employee class EmployeeInline(admin.StackedInline): model = Employee can_delete = False verbose_name_plural = 'employee' class UserAdmin(BaseUserAdmin): inlines = (EmployeeInline, ) admin.site.unregister(User) admin.site.register(User, UserAdmin) I would like to use my custom user model with some extra fields (user_photo, user_credit...), so i wrote following code; accounts/models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) photo = models.ImageField(blank=True, upload_to='prof_pic/company', default='static/images/default_pp.png') credit = models.IntegerField(default=0) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class FirmProfile(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='firmprofile_user') firm_name = models.CharField(max_length=200) class UserProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name='userprofile_user') user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES, default=1) and then accounts/admin.py class UserProfileInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'UserProfile' fk_name = 'user' class CustomUserAdmin(UserAdmin): inlines = (UserProfileInline,) model = CustomUser list_display = ('email', 'is_staff', 'is_active',) list_filter = ('email', 'is_staff', 'is_active',) fieldsets = ( (None, {'fields': ('email', 'password')}), ('Permissions', {'fields': ('is_staff', 'is_active')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2', 'is_staff', 'is_active')} ), ) search_fields = ('email',) ordering = ('email',) admin.site.register(CustomUser, CustomUserAdmin) admin.site.register(FirmProfile) But i got "no such table: main.auth_user" error when … -
it has show error when i am poting data 'str' object has no attribute 'update'
@api_view(['GET', 'POST']) def compnay_list(request): """ List all Compnays, or create a new Compnay. """ if request.method == 'GET': compnay = Company.objects.all() serializer = CompanySerializer(compnay, many=True) return Response(serializer.data) elif request.method == 'POST': try: print(request.data.get('email')) user_id = User.objects.get(email=request.data.get('email')).id print(request.data) user_response = request.data.get('user_response') for item in user_response: item.update({"user": user_id}) serializer = CompanySerializer(data=user_response) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except User.DoesNotExist: print("Error:email not available") -
How do I create a MAX value for column referring to another table's column
class Agent(models.Model): nickname = models.CharField(max_length=64) club_agent_id = models.IntegerField() club = models.ForeignKey( Club, on_delete=models.CASCADE, related_name="agents") **rakeback** = models.DecimalField(max_digits=3, decimal_places=3) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="agents") def __str__(self): return f"{self.nickname} - {self.club} - {self.rakeback}" class Account(models.Model): nickname = models.CharField(max_length=64) club_account_id = models.IntegerField() **rakeback** = models.DecimalField(max_digits=3, decimal_places=3) club = models.ManyToManyField(Club, blank=True, related_name="accounts") agent = models.ManyToManyField(Agent, related_name="accounts") def __str__(self): return f"{self.club_account_id} - {self.nickname}" Here the program will create Agent and Account are tied to it. Account belongs to Agent. Agent has many Accounts. When creating Agent, the rakeback value is set by the User. How do I set MAX for rakeback on Account referring to the value of rakeback on Agent? -
How Do We Attach a Django User to a ModelForm
Our group is working on setting up a Django Project 'for fun' having users add and remove books to sell. However, we have run into a problem of trying to assign a logged in user automatically to the book they are adding through the AddBookForm(ModelForm). Trying something along the lines of Book.objects.get(AccountUser) just returns a list of all created accounts as well as Book.objects.filter(seller=request.user). We are only looking to automatically assign the current user that is logged in when they go to add a book but have had no success reading documentations and watching tons of tutorials. Any help would be greatly appreciated!! MODEL class Book(models.Model): NEW = 'NEW' USED = 'USED' CONDITION_CHOICES = [ (NEW, 'New'), (USED, 'Used'), ] FICTION = 'FICTION' NON_FICTION = 'NON-FICTION' POETRY = 'POETRY' DRAMA = 'DRAMA' EDUCATION = 'EDUCATION' GENRE_CHOICES = [ (FICTION, 'Fiction'), (NON_FICTION, 'Non-Fiction'), (POETRY, 'Poetry'), (DRAMA, 'Drama'), (EDUCATION, 'Education'), ] class Subject(models.IntegerChoices): architecture_and_construction = 0 arts_and_digital_arts = 1 business_and_management = 2 communications_and_media = 3 computing_and_mathematics = 4 criminal_justice = 5 education_and_teaching = 6 engineering_and_technology = 7 entrepreneurship = 8 exploratory = 9 government_and_administrations = 10 health_and_wellness = 11 humanities = 12 interdisciplinary_studies = 13 law_and_public_services = 14 medical_studies_and_sciences = 15 nursing_and_health_care … -
Cant display database values in django page
models.py from future import unicode_literals from django.conf import settings import requests import json from urllib.parse import quote from django.db import models class Company(models.Model): name = models.CharField(max_length=100, db_index=True) description = models.TextField(default='1') companyPhone=models.CharField(max_length=100,blank=True) companyWebsite=models.CharField(max_length=100,blank=True) companyIsPrivate=models.BooleanField(default=True) dividend=models.DecimalField(max_digits=7, decimal_places=2) priceEarningsToGrowthAndDividendYieldRatio=models.DecimalField(max_digits=7, decimal_places=2) price=models.DecimalField(max_digits=7, decimal_places=2) numberOfEmployees=models.DecimalField(max_digits=7, decimal_places=2) type=models.CharField(max_length=100,default='2') bicsIndustry=models.CharField(max_length=100,default='3') bicsSector=models.CharField(max_length=100,default='4') companyDescription=models.TextField(default='5') companyAddress=models.TextField(default='') priceToSalesRatio=models.DecimalField(max_digits=7, decimal_places=2) priceToBookRatio=models.DecimalField(max_digits=7, decimal_places=2) priceEarningsRatio=models.DecimalField(max_digits=7, decimal_places=2) totalAssets=models.DecimalField(max_digits=7, decimal_places=2, default=0.0) volume=models.DecimalField(max_digits=7, decimal_places=2,default=0.0) is_unique = models.BooleanField(default=True) def str(self): return self.name class Meta: db_table = 'post_company' view.py from django.forms import ModelForm from django.shortcuts import get_object_or_404, render from .models import Company def my_view(request): names = request.GET.get('name') instance = Company.objects.filter(pk=names).first() class ClientForm(ModelForm): class Meta: model = Company fields= '__all__' #fields = ('name', 'description','companyPhone','companyWebsite') form = ClientForm(instance=instance) return render(request,'pdf.html', {'form': form} ) display.py {% for field in form %} {{ field.label }} {% endfor %} {% for field in form %} {{ field.value }} {% endfor %} -
How to configure Django VPS location in URL request
I am trying to configure my Django app (Djnago 3.05) to work from a server location. The location is http://dev.apps.net/tac. How do i include this in each request? I managed to do this if adding in views.py the '/tac' prefix and add a folder named 'tac' in which all the templates exist. myviews.py @login_required def item_list(request): meta = "V1.1" if not any(field in request.GET for field in set(UserFilter.get_fields())): user_list = item.objects.order_by("-date").all()[:50] else: user_list = item.objects.order_by("-date").all() user_filter = UserFilter(request.GET, queryset=user_list) return render(request, "tac/items/item_list.html", {"filter": user_filter}) urls.py urlpatterns = [ url( r"^login/$", admin_views.LoginView.as_view(template_name="registration/login.html"), name="login", ), url(r"^$", TemplateView.as_view(template_name="home.html"), name="home"), url(r"^input/$", views.inputprocess, name="inputprocess"), url(r"^items/$", views.item_list, name="item_list"), url(r"^items/create/$", views.item_create, name="item_create"), url(r"^items/(?P<pk>\d+)/update/$", views.item_update, name="item_update"), url(r"^items/(?P<pk>\d+)/delete/$", views.item_delete, name="item_delete"), url(r"^reports/$", views.reports, name="reports"), url(r"^timeline/$", views.timeline, name="timeline"), url(r"^support/$", views.support, name="support"), url(r"^dbToools/$", views.dbTools, name="dbTools"), url(r"^logout/$", views.logout_view, name="logout_view"), url(r"^upload/$", views.upload, name="upload"), path("accounts/login/", auth_views.LoginView.as_view()), path("admin/", admin.site.urls), ] I am not sure if this is the correct way. How could I do this more efficient? Could you guys please gelp me here? Thanks! -
Django Filter: __exact lookup doesn't work although no lookup works
I want to use filters on my endpoint using Django Filters. My field is a boolean field, and I justs want to filter on the exact value. When query api/mybooks?is_read=true it works (no operator --> use exact instead, it is fine) if I use the exact operator explicitely api/mybooks?is_read__exact=true it doesn't work, the filter is ignored. my filter: class MyBookFilter(django_filters.FilterSet): class Meta: model = MyBook fields = { "is_read": ["exact"], } I use the default postgres sql database. Am I missing something?