Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
KeyError "RDS_DB_NAME" when trying to connect PostgresQL with Django with Elastic Beanstalk
I have deployed my Django app (Python 3.7) with AWS Elastic Beanstalk and are trying to connect it with a postgresQL database. Following AWS' tutorial I have three files in my .ebextensions folder: 01_packages.config commands: 01_postgres_activate: command: sudo amazon-linux-extras enable postgresql10 02_postgres_install: command: sudo yum install -y postgresql-devel 03_remove_cmake: command: "yum remove cmake" packages: yum: git: [] amazon-linux-extras: [] libjpeg-turbo-devel: [] cmake3: [] gcc-c++: [] I need cmake3 and gcc-c++ for some python packages I'm running, and I'm removing cmake not to worry about a wrong version of cmake that seems to be installed by default. 02_python.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: mainapp.wsgi:application NumProcesses: 3 NumThreads: 20 aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: mainapp.settings db-migrate.config container_commands: 01_migrate: command: "python manage.py migrate" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: mainapp.settings I've added a postgresQL DB through EB console. I've also tried first activating the virtual environment in the db-migrate.config file like this: command: "source /var/app/venv/*/bin/activate && python manage.py migrate" But no success. The logs are telling me the 01_migrate command is returning an error. When I eb ssh into the EC2 instance, navigate to my app, activate the venv and then run python manage.py migrate, it gives me a KeyError that os.environ doesn't have a key named 'RDS_DB_NAME'. When … -
how do I avoid getting double array in serializer django?
I am trying to return all of the references for all of the books associated with the author, but however, I am getting an array inside array where I know its because foo in serializer, and ArrayField(models.URLField() , but I want to return as a string instead of an array of arrays. note: the API consume as a read-only so doesn't matter writeable fields class Books(models.Model): id = models.CharField(max_length=255) summary = models.TextField(blank=True, null=True) last_modified = models.DateTimeField(auto_now=True) class References(models.Model): bookid = models.ForeignKey(Vulnerabilities, on_delete=models.SET_NULL, null=True) references = ArrayField(models.URLField(),null=True, blank=True, default=list) serializer class ReferencesSerializer(serializers.ModelSerializer): class Meta: model = References fields = ("references",) class BooksSerializer(serializers.ModelSerializer): foo = serializers.SerializerMethodField() class Meta: model = Books fields = ('id','summary','foo', 'last_modified',) def get_foo(self, value): items = References.objects.filter(bookid=value) serializer = BooksSerializer(instance=items, many=True) return serializer.data viewset class BooksViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = Books.objects.all() serializer_class = BooksSerializer def get_queryset(self): search = self.request.query_params.get('search', None) if search is not None: self.queryset = self.queryset.filter( Q(summary__icontains=search) | Q(id__iexact=search) ) return self.queryset response { "count":1, "next":null, "previous":null, "results":[ { "id":"2021-3420", "summary":"", "foo":[ [ "www.google.com", "gksjksjs.com" ] ], "last_modified":"2021-03-06T00:41:00Z" } ] } -
Making form fields - read only or disabled in DJANGO updateView
I have a model which I will update using an updateView generic class based function. How can I make specific fields as read only ? example : Models.py: class Employee(models.Model): emp_no = models.IntegerField( primary_key=True) birth_date = models.DateField() first_name = models.CharField(max_length=14) last_name = models.CharField(max_length=16) gender = models.CharField(max_length=1) hire_date = models.DateField() class Meta: verbose_name = ('employee') verbose_name_plural = ('employees') # db_table = 'employees' def __str__(self): return "{} {}".format(self.first_name, self.last_name) views.py : lass EmployeeUpdate(UpdateView): model = Employee fields = '__all__' How can I make the first_name readonly inside a UpdateView ? Note: I want to have the model(charfield) the same, But it should be read only inide an UpdateView. -
ApplicantEducation matching query does not exist
This function in views.py views.py def UpdateEducation(request): context = {} user_obj = request.user if not user_obj.is_authenticated: return redirect('login') user_id = Applicant.objects.filter(app_id = user_obj.app_id).first() print(user_id) applicant = ProfileInfo.objects.filter(user=user_id).first() print(applicant) user_info = ApplicantEducation.objects.filter(applicant_info = applicant).get() if request.POST: form = EducationForm(request.POST, instance=user_info) if form.is_valid(): obj = form.save(commit=False) obj.applicant_info = applicant print(obj) obj.save() return redirect('profile') else: form = EducationForm() context['education_form'] = form else: try: form = EducationForm( initial={ 'institute_name': user_info.institute_name, 'marks_percentage' : user_info.marks_percentage, 'affilation_with' : user_info .affilation_with, 'date_completion':user_info.date_completion, 'degree_details' : user_info.degree_details, } ) context['education_form']= form except: form = EducationForm() context['education_form']= form return render(request, 'admission/signup.html', context) This model class i made for views.py models.py class DegreeDetails (models.Model): degree_name = models.CharField(max_length=10) degree_category = models.CharField(max_length= 15) def __str__(self): return '%s %s'%(self.degree_name, self.degree_category) class ApplicantEducation(models.Model): applicant_info = models.ForeignKey(ProfileInfo, on_delete=models.CASCADE) degree_details = models.ForeignKey(DegreeDetails, on_delete= models.CASCADE) marks_percentage = models.FloatField(max_length=5, default=0.0) institute_name = models.CharField(max_length=100) affilation_with = models.CharField(max_length= 50) date_completion = models.DateField(auto_now_add=False, blank=True) This is the form class for the model..... forms.py class EducationForm( forms.ModelForm): class Meta: model = ApplicantEducation fields = [ 'institute_name', 'marks_percentage', 'affilation_with', 'date_completion', 'degree_details', ] def clean(self): if self.is_valid(): institute_name = self.cleaned_data['institute_name'] marks_percentage = self.cleaned_data['marks_percentage'] affilation_with = self.cleaned_data['affilation_with'] date_completion = self.cleaned_data['date_completion'] degree_details = self.cleaned_data['degree_details'] This the error i got Error ApplicantEducation matching query does not exist. Request Method: … -
Text type hints: inspection detects names that should resolve but don't
Django 3.1.7 Pycharm Community 2020.3 ├── images │ ├── models.py │ ├── model_utils.py │ ├── tests.py │ └── views.py In the directory of 'images' application I've organized model_utils. The easiest case of a function in model_utils is for finding upload dir: def raster_img_upload_to(instance: Union["images.models.RasterImage", "images.models.ResponsiveImage"], file_name: str) -> str: responsive_image_cls = apps.get_model("images.ResponsiveImage") raster_image_cls = apps.get_model("images.RasterImage") # //@formatter:off # Assertions { assert isinstance(instance, (responsive_image_cls, raster_image_cls)) # } Assertions # //@formatter:on if isinstance(instance, responsive_image_cls): an_id = instance.raster_image.id else: an_id = instance.id result = get_image_upload_to(an_id=an_id, file_name=file_name, img_dir=general.ImgDirs.RASTER) # //@formatter:off # Assertions { assert isinstance(result, str) # } Assertions # //@formatter:on return result There are several functions of the type. That's why I moved them all in a separate package model_utils.py. The problem is that I have two warnings in PyCharm: "Unresolved reference 'images'". Correct detecting type hints errors is a key point for me. That is why I can't just ignore it. IDE's message: Unresolved reference 'images' Inspection info: This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items. One way suggested by the IDE is … -
Trying to identify the correct Python/Django unit testing solution - unittest vs pytest vs "manage.py test" vs...?
I'm new to Python and Django, as well as writing unit tests for either or both, and am trying to navigate the landscape of testing solutions as well as resolving some runtime errors (namely "Apps aren't loaded yet" when using "python -m unittest tests/tests.py"). I've been reading forum posts and tutorials for several hours and I seem to end up with more questions than answers. What I'm trying to do, as part of Agile methodology training, is implement basic get/display/show functionality on a Django model and write tests showing that the serializers are generating the proper output based on records in the database (or created by a factory and faker, which is another layer of complexity I'm attempting to wrangle). I've been advised to use AssertEquals statements to validate JSON serializer output against what's contained in a given database row, with the latter being generated by a faker, inserted via a factory and stored in a variable to use by AssertEquals when comparing values. I have an idea of the logic and how I would write it, but I'm currently getting tripped up by the errors along with trying to sort out what's the best testing framework to use and … -
Having git problem in React django project
STATEMENT I want to make project with django backend and React frontend. I have created a project using and then create a frontend react folder using create-react-app. Now I want to upload my projectname folder to my github repository. But when I add my files using git add . command from my root folder('projectname' folder). It shows some warnings given below. What should I do? Please help. WARNING hint: You've added another git repository inside your current repository. hint: Clones of the outer repository will not contain the contents of hint: the embedded repository and will not know how to obtain it. hint: If you meant to add a submodule, use: hint: hint: git submodule add <url> frontend hint: hint: If you added this path by mistake, you can remove it from the hint: index with: hint: hint: git rm --cached frontend COMMAND THAT I HAVE USED $ virtualenv env $ source env/bin/activate $ pip install django $ django-admin.py startproject projectname $ cd django-react-demo $ npm install -g create-react-app $ create-react-app frontend MY FOLDER STRUCTURE projectname │ └───frontend │ ├──.node_modules │ ├──public │ ├──src │ ├──gitignore │ ├──README.md │ ├──package.json │ └──package_lock.json │ │projectname │ ├── __init__.py │ ├── settings.py … -
Python queryto get height price user with count
I have two tables like : User: Id | Name | Age | 1 | Pankhuri | 24 2 | Neha | 23 3 | Mona | 25 And another Price log: Id | type | user_id | price | created_at| 1 | credit | 1 | 100 | 2021-03-05 12:39:43.895345 2 | credit | 2 | 50 | 2021-03-05 12:39:43.895345 3 | debit | 1 | 100 | 2021-03-04 12:39:43.895345 4 | credit | 1 | 100 | 2021-03-05 12:39:43.895345 These are my two tables from where i need to get heighst credit price user with their total price count acoording to last week date.. i want a result like : like if i want to get result for user id 1 then result should be like: pankhuri on date 04/03 price 100 and on date 5 pankhuri on date 05/03 price 200 want only heighst price user in retirn with their price total on date basisi. -
No error message, redirect to detailview using slug and get_absolut_url()
** I'm trying to link my detalview to the listview and can't understand how to redirect my title blog to the detailview template. This is my first project. I'm using slug and don't know if the problem is in hear. There's no error message. Just don't work at all. ** models.py class Story(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True, blank=True) report = models.TextField() pubdate = models.DateTimeField(auto_now=True, editable=False) author = models.ForeignKey( 'User', on_delete=models.CASCADE, blank=True, null=True ) class Meta: ordering = ['-pubdate'] def __str__(self): return self.title def get_absolute_url(self): return reverse('storiesdetail', kargs={'slug', self.slug}) urls.py urlpatterns = [ path('', views.index, name='index'), path('allauthors/', views.AuthorsList.as_view(), name='all-authors'), path('allstories/', views.StoriesList.as_view(), name='all-stories'), path( 'allstories/<slug:slug>/', views.StoriesDetail.as_view(), name='story-detail', ), ] views.py class StoriesList(ListView): models = Story template_name = 'story_list.html' queryset = Story.objects.all() context_object_name = 'stories' class StoriesDetail(DetailView): models = Story template_name = 'story_detail.html' story_list.html {% extends "base.html" %} {% block content %} <ul> {% for story in stories %} <li><a href="{{ title.get_absolute_url }}">{{ story.title }}</a> - {{ story.pubdate }} - <a href="{{ author.get_absolute_url }}">{{ story.author }}</a></li> {% empty %} <li>Sorry, no story in this list.</li> {% endfor %} </ul> {% endblock %} -
Django ImageField Template Injection
I have checked multiple sources and I can't find any pattern to how the template tags are referenced for ImageFields. Can someone please explain to me every single little part to the template tag call. For instance, {{emp.emp_image.url}} - the first spot before the period has no reference anywhere I look. Not in views, models. No references ever. The second argument is the Field in the model and then urls is a Django argument. What is the first part? {% load static %} <!DOCTYPE html> <html> <body> <h1>Name - {{emp.name}}</h1> <img src="{{emp.emp_image.url}}" alt="Smiley face" width="250" height="250"> <br /> <a href="{% url 'home' %}">Go Back!!!</a> </body> </html> -
Django Timezone Configuration
My django project is correctly enable the timezone in settings. However, the datetime field of Django ORM object is a naive datetime object as shown in Block 3. The expected result should be same as the output of Block 4 without any manually conversion. In [1]: from django.conf import settings ...: settings.USE_TZ, settings.TIME_ZONE Out[1]: (True, 'Asia/Hong_Kong') In [2]: from qms.models import Quota In [3]: q = Quota.objects.get(pk=1) ...: q.create_date, q.write_date Out[3]: (datetime.datetime(2021, 3, 10, 17, 37, 42, 489818), datetime.datetime(2021, 3, 10, 17, 37, 42, 489818)) In [4]: from django.utils import timezone ...: timezone.make_aware(q.create_date,timezone.utc), timezone.make_aware(q.write_date, time ...: zone.utc) Out[4]: (datetime.datetime(2021, 3, 10, 17, 37, 42, 489818, tzinfo=<UTC>), datetime.datetime(2021, 3, 10, 17, 37, 42, 489818, tzinfo=<UTC>)) The database schema and settings, Table "public.qms_quota" Column Type Modifiers id integer not null default nextval('qms_quota_id_seq'::regclass) create_date timestamp with time zone not null write_date timestamp with time zone not null name character varying(255) not null SHOW TIMEZONE; TimeZone ---------- UTC Questions How can I get the timezone-aware datetime object directly without any conversion? Or the manual conversion is expected ? -
Problem is that imgge is not saving . when i am select image and upload all code working propely but image does not save django
Problem is that imgge is not saving . when i am select image and upload all code working propely but image does not save. i chacked all the code line by line i am not understand wwhats the problem. i also see the media file any image is saved or not ,but there no image was saved please help me this is models.py in this file i use image field models.py class Answer (models.Model): question=models.ForeignKey(Question,on_delete=models.CASCADE) user=models.ForeignKey(User,on_delete=models.CASCADE, null=True) img=models.ImageField(null=True,blank=True,upload_to='Answer_Img') detail=RichTextUploadingField() add_time=models.DateTimeField(auto_now_add=True) def __str__(self): return self.detail forms.py class AnswerForm(ModelForm): class Meta: model=Answer fields=('detail','img') labels={'img':'Upload Image'} views.py def answer(request,pk,slug): try: trend=Question.objects.get(pk=pk,slug=slug) except: raise Http404("Post Does Not Exist") tags=trend.tags.split(',') ans=Answer.objects.filter(question=trend) answerform=AnswerForm if request.method=='POST': answerData=AnswerForm(request.POST) if answerData.is_valid(): answer=answerData.save(commit=False) answer.question=trend answer.user=request.user answer.save() p=messages.success(request,'Answer has been submitted.') return HttpResponseRedirect(trend.slug) return render(request,"ask/answer.html" ,{ 'trends':trend, 'tags':tags, 'answer':ans, 'form':answerform, }) answer.html {% if user.is_authenticated %} <div class="container"> <div class="py-5 text-center bg-secondary text-white"> <h1 class="mb-3">Upload Image</h1> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <input type="submit" class="btn btn-danger" value="Upload"> </form> </div> {% else %} <h3><P>Sign In/Sign Up before posting answers</P></h3> <h4><li><a href="{% url 'account_login' %}" class=" text-left text-info">Sign In</a></li><h4> <h4> <li><a href="{% url 'account_signup' %}" class=" text-left text-info">Sign Up</a></li><h4> {% endif %} settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = … -
trying to pass datetime into mysql table (django) but ValueError: unconverted data remains
so the time format in the data is given as: 2018-12-01T00:00:54HKT since "HKT" can't be parsed in a datetime object, i decided to replace all instances of "HKT" with a blank string and to make a naive datetime object aware. however, I kept encountering AttributeError: 'str' object has no attribute 'tzinfo' errors (the .replace(tzinfo=None) parameter doesn't seem to work for me), so i gave up on that approach and I'm just trying to convert "HKT" to GMT+0800 to parse it in as %Z to get an aware datetime object. however, this code: from mysite.models import Member, Driver, Order import json import argparse import django from django.conf import settings from django.utils import timezone import sys import os #from datetime import datetime #from pytz import timezone import pytz import datetime import pymysql pymysql.install_as_MySQLdb() for member in data: data_members = {} if 'memberID' in member: data_members['memberID'] = member['memberID'] if 'createdTime' in member: #createdTime = str(member['createdTime']) createdTime = str(member['createdTime']).replace("HKT", "GMT+0800") # remove so time can be parsed as datetime object #print(createdTime) createdTime = datetime.datetime.strptime(createdTime, "%Y-%m-%dT%H:%M:%S%Z") print(createdTime) #print(type(createdTime)) # type datetime object createdTime = createdTime.strftime(datetime_format) aware_createdTime = timezone.make_aware(createdTime, hkt) #print(type(createdTime)) # type string #print(createdTime) # createdTime = createdTime.replace(tzinfo=hkt) # createdTime = createdTime.astimezone(hkt) # createdTime_aware = … -
My view object has no attribute 'META', why is this happening?
I run into AttributeError: 'ConstanciaInscripcion' object has no attribute 'META' when I try to post my request. I am not sure what happened because it was working perfectly fine until today. Is the error in the view or somewhere else? I says " 'ip': lambda r: ip_mask(r.META['REMOTE_ADDR']), " right before the error so maybe that's related to it? What's wrong with the code? This is the view: from django.shortcuts import render, HttpResponse import requests from django.views.generic import FormView from .forms import MonotributoForm from app.ws_sr_padron import ws_sr_padron13_get_persona from app.captcha import resolve_simple_captcha from app.constancia_email import constancia_email from ratelimit.decorators import ratelimit #selenium from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from time import sleep #screenshot pdf import io from PIL import Image from importlib import reload import sys class ConstanciaInscripcion(FormView): def get(self, request): return render(request, 'app/constancia-inscripcion.html') @ratelimit(key='ip', rate='3/d') def post(self,request): form = MonotributoForm(request.POST) email = request.POST['Email'] #Verificar cuit en padron13 una vez que es ingresado cuit_r = int(request.POST["CUIT"]) response = ws_sr_padron13_get_persona(cuit_r) try: nombre = response["persona"]["nombre"] apellido = response["persona"]["apellido"] cuit = response["persona"]["tipoClave"] except KeyError: nombre, apellido = None, None print("El CUIT ingresado es incorrecto") except TypeError: nombre, apellido = None, None print("El CUIT ingresado … -
why this problem while using Django Rest Framework
module rest_framework unresolved import 'rest_framework'Python(unresolved-import) No quick fixes available -
django upload file godaddy hosting
I have a running django on my pc no problem with upload 1 video large file but on godaddy hosting return 413.html to my browser i setting php selector but not work my php setting my page -
Adding accept on Django model FileField
Good day SO. I found this accepted answer on how to add attrs accept for my filefield. This is how I did it on my project. model: curriculum_vitae = models.FileField(upload_to=img_path, validators=[validate_file_extension], null=True, blank=True) Forms: class SomeClass(forms.ModelForm): curriculum_vitae = forms.FileField(label=('Curriculum Vitae'),required=False, error_messages = {'invalid':("Document Files only")}, widget=forms.FileInput(attrs={'accept':'pdf/*,doc/*,docx/*,xlsx/*,xls/*'})) class Meta: ... However, on my template, my fieldfield only has All Files(*,*). Any idea what I did wrong? -
RelatedObjectDoesNotExist at / Accounts has no customer
[enter image description here][1] **strong text** [1]: https://i.stack.imgur.com/XhO71.png The problem arises while creating new users. It says related object does not exist. accounts model class Accounts(AbstractBaseUser): username = models.CharField(max_length=30, unique=True) email = models.EmailField(verbose_name="email", max_length=60, unique=True) date_created = models.DateTimeField( verbose_name='date_joined', auto_now_add=True) last_login = models.DateTimeField( verbose_name='last_login', auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) # setting username as a key to login. Note: email can also be used in it USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['first_name', 'last_name', 'email'] store model class Customer(models.Model): username = models.OneToOneField( Accounts, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, null=True) email = models.CharField(max_length=100, null=True) def __str__(self): return self.name -
How can I expose media folder in django?
I have a running django project on my server's port 8800, while I also expose a static media folder on the same server on port 8000. In this way, I would be able to view the folder/directory listing via HTTP on the web browser. To do the latter (exposing the media directory), I run the below command: python -m http.server -d "D:\media" 8000 My question is how can I incorporate doing both on the same port? Or, how can I expose the target media folder just by running the django project? Any clue or feedback will be much appreciated. Thank you very much. -
Django : Foreign Key to a choice field model
I am relatively new to Python / Django. I am trying to create a relationship between food items and the category (name) they belong: class Category(models.Model): options=( ('vegetable','vegetable'), ('fruit','fruit'), ('carbs','carbs'), ('fish','fish'), ('meat', 'meat'), ('sweet', 'sweet'), ('dairy', 'dairy'), ) name=models.CharField(max_length=10,choices=options,unique=True) def __str__(self): return self.name class Fooditem(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category,on_delete=models.CASCADE) The code above throws error when running migrate: ValueError: invalid literal for int() with base 10: 'vegetable' I created some items in the database, is it the reason? What is the best way to solve this problem? Thank you, D -
django clean_field not reading a form field
I want my code to raise an error if: User selected role=="Other" AND they left field "other_role" blank. I made a clean function, but when I try and reference the field "other_role", it always shows up as None, even when the form is filled. How can I reference another field? PS: I don't want to have to explicitly define that field again in my form class because that will mess up the order my forms are rendered. class AttendeeForm(forms.ModelForm): # birth_date = forms.DateField(widget=forms.TextInput(attrs={ # 'class':'datepicker' #})) class Meta: model = Attendee fields= ('birth_date', 'degrees','area_of_study','role','other_role','institute', 'phone_number') widgets = { 'birth_date': DateInput() } help_texts = { 'degrees': 'List your degrees. Separate with commas.', 'area_of_study': 'List your primary field of study or research. If neither are applicable, write your area of practice.', 'institute': 'Professional Affiliation. If retired, enter your most recent affiliation.' } def clean_role(self): cd = self.cleaned_data print(cd.get("other_role")) if cd['role'] == 'OTHER': if cd.get("other_role") is not False: raise forms.ValidationError("You need to specify your role if you picked 'Other'") return cd['role'] -
TypeError: AuthMiddlewareStack() missing 1 required positional argument: 'inner'
Hi I am trying to build ASGI APPLICATION but I get this error File "/home/marwan/Desktop/Gowd/gowd_project/config/routing.py", line 8, in <module> AuthMiddlewareStack( TypeError: AuthMiddlewareStack() missing 1 required positional argument: 'inner' and this is my routing.py file from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.urls import path application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( # URLRouter([...]) # Empty for now because we don't have a consumer yet. ) ) }) -
SQL to Django Translation
This statement works in SQL, I just cannot figure out how to convert it to django. Im sure it uses prefetch_related, Prefetch, or select_related but im still having a hard time understanding those concepts. I do see that prefetch basically has to have the field under that table. My goal: Not all brands have products. All products have brands. Show my only brands with products. I was hoping to implement Brand.objects.[insert-filter-here] Model.py (appended version of actual models.py file) class Product(models.Model): brand = models.ForeignKey(Brand) class Brand(models.Model): name = models.CharField SQL SELECT DISTINCT products_brand.name FROM produts_brand INNER JOIN products_product on products_brand.id=products_product.brand_id; Its 2 tables becuase the products table has many many columns (27), I guess the other option is to just combine them. But I wanted more control over Brand objects for ease of lookup/editing. Many thanks for your help! -
What languages and frameworks are best suitable for complex applications?
I worked on a few projects with python and its web framework django and therefore became very fluent with it. The same applies to php (but without frameworks like laravel, just plain php 3rd party modules). But I found out that python/django might not be good for a lot of traffic/requests and so might abandon incoming requests. But the core of such complex applications lies in the backend: processing a lot of concurrent user requests (database queries, read and write (equal amount of read/write requests)), authentication system and safety, fast template rendering fast time to first byte . . . I know that python is a high level language and therefore might be slower but is there a better language suitable to use as the core stack for the backend (serving both mobile app and web app) being faster reliable and highly scalable? Can you give me examples for which languages and frameworks big apps like instagram, facebook, youtube and co. are using to be high performing even on high amounts -
Once set Username=None. it is not a undo able after migrations + migrate
class User(AbstractUser): name = models.CharField(max_length=255, null=True) email = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) username= None status = models.IntegerField(null=True, blank=True, default=2) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] After migrate in this i lost username field and i cannot get this field back also check my migration file operations = [ migrations.RemoveField( model_name='user', name='username', ), ] what should i do? to get back my username field again. Thanks